Realcat commited on
Commit
4bde5d3
·
1 Parent(s): de498de

init: files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ build/
2
+ # lib
3
+ bin/
4
+ cmake_modules/
5
+ cmake-build-debug/
6
+ .idea/
7
+ .vscode/
8
+ *.pyc
9
+ flagged
10
+ .ipynb_checkpoints
11
+ __pycache__
12
+ Untitled*
13
+ experiments
14
+ third_party/REKD
15
+ hloc/matchers/dedode.py
16
+ gradio_cached_examples
17
+ *.mp4
18
+ hloc/matchers/quadtree.py
19
+ third_party/QuadTreeAttention
20
+ desktop.ini
21
+ *.egg-info
22
+ output.pkl
23
+ log.txt
24
+ experiments*
25
+ gen_example.py
26
+ datasets/lines/terrace0.JPG
27
+ datasets/lines/terrace1.JPG
28
+ datasets/South-Building*
Dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official conda-based Python image as a parent image
2
+ FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime
3
+ LABEL maintainer vincentqyw
4
+ ARG PYTHON_VERSION=3.10.10
5
+
6
+ # Set the working directory to /code
7
+ WORKDIR /code
8
+
9
+ # Install Git and Git LFS
10
+ RUN apt-get update && apt-get install -y git-lfs
11
+ RUN git lfs install
12
+
13
+ # Clone the Git repository
14
+ RUN git clone https://huggingface.co/spaces/Realcat/image-matching-webui /code
15
+
16
+ RUN conda create -n imw python=${PYTHON_VERSION}
17
+ RUN echo "source activate imw" > ~/.bashrc
18
+ ENV PATH /opt/conda/envs/imw/bin:$PATH
19
+
20
+ # Make RUN commands use the new environment
21
+ SHELL ["conda", "run", "-n", "imw", "/bin/bash", "-c"]
22
+ RUN pip install --upgrade pip
23
+ RUN pip install -r requirements.txt
24
+ RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
25
+
26
+ # Export port
27
+ EXPOSE 7860
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.
README.md CHANGED
@@ -1,12 +1,155 @@
1
  ---
2
  title: Imatchui
3
- emoji: 🐨
4
  colorFrom: red
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 5.4.0
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: Imatchui
3
+ emoji: 🤗
4
  colorFrom: red
5
+ colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.4.0
8
  app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
  ---
12
 
13
+ [![Contributors][contributors-shield]][contributors-url]
14
+ [![Forks][forks-shield]][forks-url]
15
+ [![Stargazers][stars-shield]][stars-url]
16
+ [![Issues][issues-shield]][issues-url]
17
+
18
+ <p align="center">
19
+ <h1 align="center"><br><ins>Image Matching WebUI</ins><br>Identify matching points between two images</h1>
20
+ </p>
21
+
22
+ ## Description
23
+
24
+ This simple tool efficiently matches image pairs using multiple famous image matching algorithms. The tool features a Graphical User Interface (GUI) designed using [gradio](https://gradio.app/). You can effortlessly select two images and a matching algorithm and obtain a precise matching result.
25
+ **Note**: the images source can be either local images or webcam images.
26
+
27
+ Try it on <a href='https://huggingface.co/spaces/Realcat/image-matching-webui'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a>
28
+ <a target="_blank" href="https://lightning.ai/realcat/studios/image-matching-webui">
29
+ <img src="https://pl-bolts-doc-images.s3.us-east-2.amazonaws.com/app-2/studio-badge.svg" alt="Open In Studio"/>
30
+ </a>
31
+
32
+ Here is a demo of the tool:
33
+
34
+ ![demo](assets/demo.gif)
35
+
36
+ The tool currently supports various popular image matching algorithms, namely:
37
+ - [x] [EfficientLoFTR](https://github.com/zju3dv/EfficientLoFTR), CVPR 2024
38
+ - [x] [MASt3R](https://github.com/naver/mast3r), CVPR 2024
39
+ - [x] [DUSt3R](https://github.com/naver/dust3r), CVPR 2024
40
+ - [x] [OmniGlue](https://github.com/Vincentqyw/omniglue-onnx), CVPR 2024
41
+ - [x] [XFeat](https://github.com/verlab/accelerated_features), CVPR 2024
42
+ - [x] [RoMa](https://github.com/Vincentqyw/RoMa), CVPR 2024
43
+ - [x] [DeDoDe](https://github.com/Parskatt/DeDoDe), 3DV 2024
44
+ - [ ] [Mickey](https://github.com/nianticlabs/mickey), CVPR 2024
45
+ - [x] [GIM](https://github.com/xuelunshen/gim), ICLR 2024
46
+ - [ ] [DUSt3R](https://github.com/naver/dust3r), arXiv 2023
47
+ - [x] [LightGlue](https://github.com/cvg/LightGlue), ICCV 2023
48
+ - [x] [DarkFeat](https://github.com/THU-LYJ-Lab/DarkFeat), AAAI 2023
49
+ - [x] [SFD2](https://github.com/feixue94/sfd2), CVPR 2023
50
+ - [x] [IMP](https://github.com/feixue94/imp-release), CVPR 2023
51
+ - [ ] [ASTR](https://github.com/ASTR2023/ASTR), CVPR 2023
52
+ - [ ] [SEM](https://github.com/SEM2023/SEM), CVPR 2023
53
+ - [ ] [DeepLSD](https://github.com/cvg/DeepLSD), CVPR 2023
54
+ - [x] [GlueStick](https://github.com/cvg/GlueStick), ICCV 2023
55
+ - [ ] [ConvMatch](https://github.com/SuhZhang/ConvMatch), AAAI 2023
56
+ - [x] [LoFTR](https://github.com/zju3dv/LoFTR), CVPR 2021
57
+ - [x] [SOLD2](https://github.com/cvg/SOLD2), CVPR 2021
58
+ - [ ] [LineTR](https://github.com/yosungho/LineTR), RA-L 2021
59
+ - [x] [DKM](https://github.com/Parskatt/DKM), CVPR 2023
60
+ - [ ] [NCMNet](https://github.com/xinliu29/NCMNet), CVPR 2023
61
+ - [x] [TopicFM](https://github.com/Vincentqyw/TopicFM), AAAI 2023
62
+ - [x] [AspanFormer](https://github.com/Vincentqyw/ml-aspanformer), ECCV 2022
63
+ - [x] [LANet](https://github.com/wangch-g/lanet), ACCV 2022
64
+ - [ ] [LISRD](https://github.com/rpautrat/LISRD), ECCV 2022
65
+ - [ ] [REKD](https://github.com/bluedream1121/REKD), CVPR 2022
66
+ - [x] [CoTR](https://github.com/ubc-vision/COTR), ICCV 2021
67
+ - [x] [ALIKE](https://github.com/Shiaoming/ALIKE), TMM 2022
68
+ - [x] [RoRD](https://github.com/UditSinghParihar/RoRD), IROS 2021
69
+ - [x] [SGMNet](https://github.com/vdvchen/SGMNet), ICCV 2021
70
+ - [x] [SuperPoint](https://github.com/magicleap/SuperPointPretrainedNetwork), CVPRW 2018
71
+ - [x] [SuperGlue](https://github.com/magicleap/SuperGluePretrainedNetwork), CVPR 2020
72
+ - [x] [D2Net](https://github.com/Vincentqyw/d2-net), CVPR 2019
73
+ - [x] [R2D2](https://github.com/naver/r2d2), NeurIPS 2019
74
+ - [x] [DISK](https://github.com/cvlab-epfl/disk), NeurIPS 2020
75
+ - [ ] [Key.Net](https://github.com/axelBarroso/Key.Net), ICCV 2019
76
+ - [ ] [OANet](https://github.com/zjhthu/OANet), ICCV 2019
77
+ - [x] [SOSNet](https://github.com/scape-research/SOSNet), CVPR 2019
78
+ - [x] [HardNet](https://github.com/DagnyT/hardnet), NeurIPS 2017
79
+ - [x] [SIFT](https://docs.opencv.org/4.x/da/df5/tutorial_py_sift_intro.html), IJCV 2004
80
+
81
+ ## How to use
82
+
83
+ ### HuggingFace / Lightning AI
84
+
85
+ Just try it on <a href='https://huggingface.co/spaces/Realcat/image-matching-webui'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a>
86
+ <a target="_blank" href="https://lightning.ai/realcat/studios/image-matching-webui">
87
+ <img src="https://pl-bolts-doc-images.s3.us-east-2.amazonaws.com/app-2/studio-badge.svg" alt="Open In Studio"/>
88
+ </a>
89
+
90
+ or deploy it locally following the instructions below.
91
+
92
+ ### Requirements
93
+ ``` bash
94
+ git clone --recursive https://github.com/Vincentqyw/image-matching-webui.git
95
+ cd image-matching-webui
96
+ conda env create -f environment.yaml
97
+ conda activate imw
98
+ ```
99
+
100
+ or using [docker](https://hub.docker.com/r/vincentqin/image-matching-webui):
101
+
102
+ ``` bash
103
+ docker pull vincentqin/image-matching-webui:latest
104
+ docker run -it -p 7860:7860 vincentqin/image-matching-webui:latest python app.py --server_name "0.0.0.0" --server_port=7860
105
+ ```
106
+
107
+ ### Run demo
108
+ ``` bash
109
+ python3 ./app.py
110
+ ```
111
+ then open http://localhost:7860 in your browser.
112
+
113
+ ![](assets/gui.jpg)
114
+
115
+ ### Add your own feature / matcher
116
+
117
+ I provide an example to add local feature in [hloc/extractors/example.py](hloc/extractors/example.py). Then add feature settings in `confs` in file [hloc/extract_features.py](hloc/extract_features.py). Last step is adding some settings to `model_zoo` in file [ui/config.yaml](ui/config.yaml).
118
+
119
+ ## Contributions welcome!
120
+
121
+ External contributions are very much welcome. Please follow the [PEP8 style guidelines](https://www.python.org/dev/peps/pep-0008/) using a linter like flake8 (reformat using command `python -m black .`). This is a non-exhaustive list of features that might be valuable additions:
122
+
123
+ - [x] add webcam support
124
+ - [x] add [line feature matching](https://github.com/Vincentqyw/LineSegmentsDetection) algorithms
125
+ - [x] example to add a new feature extractor / matcher
126
+ - [x] ransac to filter outliers
127
+ - [ ] add [rotation images](https://github.com/pidahbus/deep-image-orientation-angle-detection) options before matching
128
+ - [ ] support export matches to colmap ([#issue 6](https://github.com/Vincentqyw/image-matching-webui/issues/6))
129
+ - [ ] add config file to set default parameters
130
+ - [ ] dynamically load models and reduce GPU overload
131
+
132
+ Adding local features / matchers as submodules is very easy. For example, to add the [GlueStick](https://github.com/cvg/GlueStick):
133
+
134
+ ``` bash
135
+ git submodule add https://github.com/cvg/GlueStick.git third_party/GlueStick
136
+ ```
137
+
138
+ If remote submodule repositories are updated, don't forget to pull submodules with `git submodule update --remote`, if you only want to update one submodule, use `git submodule update --remote third_party/GlueStick`.
139
+
140
+ ## Resources
141
+ - [Image Matching: Local Features & Beyond](https://image-matching-workshop.github.io)
142
+ - [Long-term Visual Localization](https://www.visuallocalization.net)
143
+
144
+ ## Acknowledgement
145
+
146
+ This code is built based on [Hierarchical-Localization](https://github.com/cvg/Hierarchical-Localization). We express our gratitude to the authors for their valuable source code.
147
+
148
+ [contributors-shield]: https://img.shields.io/github/contributors/Vincentqyw/image-matching-webui.svg?style=for-the-badge
149
+ [contributors-url]: https://github.com/Vincentqyw/image-matching-webui/graphs/contributors
150
+ [forks-shield]: https://img.shields.io/github/forks/Vincentqyw/image-matching-webui.svg?style=for-the-badge
151
+ [forks-url]: https://github.com/Vincentqyw/image-matching-webui/network/members
152
+ [stars-shield]: https://img.shields.io/github/stars/Vincentqyw/image-matching-webui.svg?style=for-the-badge
153
+ [stars-url]: https://github.com/Vincentqyw/image-matching-webui/stargazers
154
+ [issues-shield]: https://img.shields.io/github/issues/Vincentqyw/image-matching-webui.svg?style=for-the-badge
155
+ [issues-url]: https://github.com/Vincentqyw/image-matching-webui/issues
api/__init__.py ADDED
File without changes
api/client.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
124
+ f"Error: Response code {response.status_code} - {response.text}"
125
+ )
126
+ finally:
127
+ files["image0"].close()
128
+ files["image1"].close()
129
+ return pred
130
+
131
+
132
+ def send_request_extract(
133
+ input_images: str, viz: bool = False
134
+ ) -> List[Dict[str, np.ndarray]]:
135
+ """
136
+ Send a request to the API to extract features from an image.
137
+
138
+ Args:
139
+ input_images (str): The path to the image.
140
+
141
+ Returns:
142
+ List[Dict[str, np.ndarray]]: A list of dictionaries containing the
143
+ extracted features. The keys are "keypoints", "descriptors", and
144
+ "scores", and the values are ndarrays of shape (N, 2), (N, 128),
145
+ and (N,), respectively.
146
+ """
147
+ image_data = read_image(input_images)
148
+ inputs = {
149
+ "data": [image_data],
150
+ }
151
+ response = do_api_requests(
152
+ url=API_URL_EXTRACT,
153
+ **inputs,
154
+ )
155
+ print("Keypoints detected: {}".format(len(response[0]["keypoints"])))
156
+
157
+ # draw matching, debug only
158
+ if viz:
159
+ from hloc.utils.viz import plot_keypoints
160
+ from ui.viz import fig2im, plot_images
161
+
162
+ kpts = np.array(response[0]["keypoints_orig"])
163
+ if "image_orig" in response[0].keys():
164
+ img_orig = np.array(["image_orig"])
165
+
166
+ output_keypoints = plot_images([img_orig], titles="titles", dpi=300)
167
+ plot_keypoints([kpts])
168
+ output_keypoints = fig2im(output_keypoints)
169
+ cv2.imwrite(
170
+ "demo_match.jpg",
171
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
172
+ )
173
+ return response
174
+
175
+
176
+ def get_api_version():
177
+ try:
178
+ response = requests.get(API_VERSION).json()
179
+ print("API VERSION: {}".format(response["version"]))
180
+ except Exception as e:
181
+ print(f"An error occurred: {e}")
182
+
183
+
184
+ if __name__ == "__main__":
185
+ parser = argparse.ArgumentParser(
186
+ description="Send text to stable audio server and receive generated audio."
187
+ )
188
+ parser.add_argument(
189
+ "--image0",
190
+ required=False,
191
+ help="Path for the file's melody",
192
+ default="datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot45.jpg",
193
+ )
194
+ parser.add_argument(
195
+ "--image1",
196
+ required=False,
197
+ help="Path for the file's melody",
198
+ default="datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot90.jpg",
199
+ )
200
+ args = parser.parse_args()
201
+
202
+ # get api version
203
+ get_api_version()
204
+
205
+ # request match
206
+ # for i in range(10):
207
+ # t1 = time.time()
208
+ # preds = send_request_match(args.image0, args.image1)
209
+ # t2 = time.time()
210
+ # print(
211
+ # "Time cost1: {} seconds, matched: {}".format(
212
+ # (t2 - t1), len(preds["mmkeypoints0_orig"])
213
+ # )
214
+ # )
215
+
216
+ # request extract
217
+ for i in range(10):
218
+ t1 = time.time()
219
+ preds = send_request_extract(args.image0)
220
+ t2 = time.time()
221
+ print(f"Time cost2: {(t2 - t1)} seconds")
222
+
223
+ # dump preds
224
+ with open("preds.pkl", "wb") as f:
225
+ pickle.dump(preds, f)
api/server.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # server.py
2
+ import base64
3
+ import io
4
+ import sys
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional, Union
8
+
9
+ import cv2
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import torch
13
+ import uvicorn
14
+ from fastapi import FastAPI, File, UploadFile
15
+ from fastapi.exceptions import HTTPException
16
+ from fastapi.responses import JSONResponse
17
+ from PIL import Image
18
+
19
+ sys.path.append(str(Path(__file__).parents[1]))
20
+
21
+ from api.types import ImagesInput
22
+ from hloc import DEVICE, extract_features, logger, match_dense, match_features
23
+ from hloc.utils.viz import add_text, plot_keypoints
24
+ from ui import get_version
25
+ from ui.utils import filter_matches, get_feature_model, get_model
26
+ from ui.viz import display_matches, fig2im, plot_images
27
+
28
+ warnings.simplefilter("ignore")
29
+
30
+
31
+ def decode_base64_to_image(encoding):
32
+ if encoding.startswith("data:image/"):
33
+ encoding = encoding.split(";")[1].split(",")[1]
34
+ try:
35
+ image = Image.open(io.BytesIO(base64.b64decode(encoding)))
36
+ return image
37
+ except Exception as e:
38
+ logger.warning(f"API cannot decode image: {e}")
39
+ raise HTTPException(
40
+ status_code=500, detail="Invalid encoded image"
41
+ ) from e
42
+
43
+
44
+ def to_base64_nparray(encoding: str) -> np.ndarray:
45
+ return np.array(decode_base64_to_image(encoding)).astype("uint8")
46
+
47
+
48
+ class ImageMatchingAPI(torch.nn.Module):
49
+ default_conf = {
50
+ "ransac": {
51
+ "enable": True,
52
+ "estimator": "poselib",
53
+ "geometry": "homography",
54
+ "method": "RANSAC",
55
+ "reproj_threshold": 3,
56
+ "confidence": 0.9999,
57
+ "max_iter": 10000,
58
+ },
59
+ }
60
+
61
+ def __init__(
62
+ self,
63
+ conf: dict = {},
64
+ device: str = "cpu",
65
+ detect_threshold: float = 0.015,
66
+ max_keypoints: int = 1024,
67
+ match_threshold: float = 0.2,
68
+ ) -> None:
69
+ """
70
+ Initializes an instance of the ImageMatchingAPI class.
71
+
72
+ Args:
73
+ conf (dict): A dictionary containing the configuration parameters.
74
+ device (str, optional): The device to use for computation. Defaults to "cpu".
75
+ detect_threshold (float, optional): The threshold for detecting keypoints. Defaults to 0.015.
76
+ max_keypoints (int, optional): The maximum number of keypoints to extract. Defaults to 1024.
77
+ match_threshold (float, optional): The threshold for matching keypoints. Defaults to 0.2.
78
+
79
+ Returns:
80
+ None
81
+ """
82
+ super().__init__()
83
+ self.device = device
84
+ self.conf = {**self.default_conf, **conf}
85
+ self._updata_config(detect_threshold, max_keypoints, match_threshold)
86
+ self._init_models()
87
+ if device == "cuda":
88
+ memory_allocated = torch.cuda.memory_allocated(device)
89
+ memory_reserved = torch.cuda.memory_reserved(device)
90
+ logger.info(
91
+ f"GPU memory allocated: {memory_allocated / 1024**2:.3f} MB"
92
+ )
93
+ logger.info(
94
+ f"GPU memory reserved: {memory_reserved / 1024**2:.3f} MB"
95
+ )
96
+ self.pred = None
97
+
98
+ def parse_match_config(self, conf):
99
+ if conf["dense"]:
100
+ return {
101
+ **conf,
102
+ "matcher": match_dense.confs.get(
103
+ conf["matcher"]["model"]["name"]
104
+ ),
105
+ "dense": True,
106
+ }
107
+ else:
108
+ return {
109
+ **conf,
110
+ "feature": extract_features.confs.get(
111
+ conf["feature"]["model"]["name"]
112
+ ),
113
+ "matcher": match_features.confs.get(
114
+ conf["matcher"]["model"]["name"]
115
+ ),
116
+ "dense": False,
117
+ }
118
+
119
+ def _updata_config(
120
+ self,
121
+ detect_threshold: float = 0.015,
122
+ max_keypoints: int = 1024,
123
+ match_threshold: float = 0.2,
124
+ ):
125
+ self.dense = self.conf["dense"]
126
+ if self.conf["dense"]:
127
+ try:
128
+ self.conf["matcher"]["model"][
129
+ "match_threshold"
130
+ ] = match_threshold
131
+ except TypeError as e:
132
+ logger.error(e)
133
+ else:
134
+ self.conf["feature"]["model"]["max_keypoints"] = max_keypoints
135
+ self.conf["feature"]["model"][
136
+ "keypoint_threshold"
137
+ ] = detect_threshold
138
+ self.extract_conf = self.conf["feature"]
139
+
140
+ self.match_conf = self.conf["matcher"]
141
+
142
+ def _init_models(self):
143
+ # initialize matcher
144
+ self.matcher = get_model(self.match_conf)
145
+ # initialize extractor
146
+ if self.dense:
147
+ self.extractor = None
148
+ else:
149
+ self.extractor = get_feature_model(self.conf["feature"])
150
+
151
+ def _forward(self, img0, img1):
152
+ if self.dense:
153
+ pred = match_dense.match_images(
154
+ self.matcher,
155
+ img0,
156
+ img1,
157
+ self.match_conf["preprocessing"],
158
+ device=self.device,
159
+ )
160
+ last_fixed = "{}".format( # noqa: F841
161
+ self.match_conf["model"]["name"]
162
+ )
163
+ else:
164
+ pred0 = extract_features.extract(
165
+ self.extractor, img0, self.extract_conf["preprocessing"]
166
+ )
167
+ pred1 = extract_features.extract(
168
+ self.extractor, img1, self.extract_conf["preprocessing"]
169
+ )
170
+ pred = match_features.match_images(self.matcher, pred0, pred1)
171
+ return pred
172
+
173
+ @torch.inference_mode()
174
+ def extract(self, img0: np.ndarray, **kwargs) -> Dict[str, np.ndarray]:
175
+ """Extract features from a single image.
176
+
177
+ Args:
178
+ img0 (np.ndarray): image
179
+
180
+ Returns:
181
+ Dict[str, np.ndarray]: feature dict
182
+ """
183
+
184
+ # setting prams
185
+ self.extractor.conf["max_keypoints"] = kwargs.get("max_keypoints", 512)
186
+ self.extractor.conf["keypoint_threshold"] = kwargs.get(
187
+ "keypoint_threshold", 0.0
188
+ )
189
+
190
+ pred = extract_features.extract(
191
+ self.extractor, img0, self.extract_conf["preprocessing"]
192
+ )
193
+ pred = {
194
+ k: v.cpu().detach()[0].numpy() if isinstance(v, torch.Tensor) else v
195
+ for k, v in pred.items()
196
+ }
197
+ # back to origin scale
198
+ s0 = pred["original_size"] / pred["size"]
199
+ pred["keypoints_orig"] = (
200
+ match_features.scale_keypoints(pred["keypoints"] + 0.5, s0) - 0.5
201
+ )
202
+ # TODO: rotate back
203
+
204
+ binarize = kwargs.get("binarize", False)
205
+ if binarize:
206
+ assert "descriptors" in pred
207
+ pred["descriptors"] = (pred["descriptors"] > 0).astype(np.uint8)
208
+ pred["descriptors"] = pred["descriptors"].T # N x DIM
209
+ return pred
210
+
211
+ @torch.inference_mode()
212
+ def forward(
213
+ self,
214
+ img0: np.ndarray,
215
+ img1: np.ndarray,
216
+ ) -> Dict[str, np.ndarray]:
217
+ """
218
+ Forward pass of the image matching API.
219
+
220
+ Args:
221
+ img0: A 3D NumPy array of shape (H, W, C) representing the first image.
222
+ Values are in the range [0, 1] and are in RGB mode.
223
+ img1: A 3D NumPy array of shape (H, W, C) representing the second image.
224
+ Values are in the range [0, 1] and are in RGB mode.
225
+
226
+ Returns:
227
+ A dictionary containing the following keys:
228
+ - image0_orig: The original image 0.
229
+ - image1_orig: The original image 1.
230
+ - keypoints0_orig: The keypoints detected in image 0.
231
+ - keypoints1_orig: The keypoints detected in image 1.
232
+ - mkeypoints0_orig: The raw matches between image 0 and image 1.
233
+ - mkeypoints1_orig: The raw matches between image 1 and image 0.
234
+ - mmkeypoints0_orig: The RANSAC inliers in image 0.
235
+ - mmkeypoints1_orig: The RANSAC inliers in image 1.
236
+ - mconf: The confidence scores for the raw matches.
237
+ - mmconf: The confidence scores for the RANSAC inliers.
238
+ """
239
+ # Take as input a pair of images (not a batch)
240
+ assert isinstance(img0, np.ndarray)
241
+ assert isinstance(img1, np.ndarray)
242
+ self.pred = self._forward(img0, img1)
243
+ if self.conf["ransac"]["enable"]:
244
+ self.pred = self._geometry_check(self.pred)
245
+ return self.pred
246
+
247
+ def _geometry_check(
248
+ self,
249
+ pred: Dict[str, Any],
250
+ ) -> Dict[str, Any]:
251
+ """
252
+ Filter matches using RANSAC. If keypoints are available, filter by keypoints.
253
+ If lines are available, filter by lines. If both keypoints and lines are
254
+ available, filter by keypoints.
255
+
256
+ Args:
257
+ pred (Dict[str, Any]): dict of matches, including original keypoints.
258
+ See :func:`filter_matches` for the expected keys.
259
+
260
+ Returns:
261
+ Dict[str, Any]: filtered matches
262
+ """
263
+ pred = filter_matches(
264
+ pred,
265
+ ransac_method=self.conf["ransac"]["method"],
266
+ ransac_reproj_threshold=self.conf["ransac"]["reproj_threshold"],
267
+ ransac_confidence=self.conf["ransac"]["confidence"],
268
+ ransac_max_iter=self.conf["ransac"]["max_iter"],
269
+ )
270
+ return pred
271
+
272
+ def visualize(
273
+ self,
274
+ log_path: Optional[Path] = None,
275
+ ) -> None:
276
+ """
277
+ Visualize the matches.
278
+
279
+ Args:
280
+ log_path (Path, optional): The directory to save the images. Defaults to None.
281
+
282
+ Returns:
283
+ None
284
+ """
285
+ if self.conf["dense"]:
286
+ postfix = str(self.conf["matcher"]["model"]["name"])
287
+ else:
288
+ postfix = "{}_{}".format(
289
+ str(self.conf["feature"]["model"]["name"]),
290
+ str(self.conf["matcher"]["model"]["name"]),
291
+ )
292
+ titles = [
293
+ "Image 0 - Keypoints",
294
+ "Image 1 - Keypoints",
295
+ ]
296
+ pred: Dict[str, Any] = self.pred
297
+ image0: np.ndarray = pred["image0_orig"]
298
+ image1: np.ndarray = pred["image1_orig"]
299
+ output_keypoints: np.ndarray = plot_images(
300
+ [image0, image1], titles=titles, dpi=300
301
+ )
302
+ if (
303
+ "keypoints0_orig" in pred.keys()
304
+ and "keypoints1_orig" in pred.keys()
305
+ ):
306
+ plot_keypoints([pred["keypoints0_orig"], pred["keypoints1_orig"]])
307
+ text: str = (
308
+ f"# keypoints0: {len(pred['keypoints0_orig'])} \n"
309
+ + f"# keypoints1: {len(pred['keypoints1_orig'])}"
310
+ )
311
+ add_text(0, text, fs=15)
312
+ output_keypoints = fig2im(output_keypoints)
313
+ # plot images with raw matches
314
+ titles = [
315
+ "Image 0 - Raw matched keypoints",
316
+ "Image 1 - Raw matched keypoints",
317
+ ]
318
+ output_matches_raw, num_matches_raw = display_matches(
319
+ pred, titles=titles, tag="KPTS_RAW"
320
+ )
321
+ # plot images with ransac matches
322
+ titles = [
323
+ "Image 0 - Ransac matched keypoints",
324
+ "Image 1 - Ransac matched keypoints",
325
+ ]
326
+ output_matches_ransac, num_matches_ransac = display_matches(
327
+ pred, titles=titles, tag="KPTS_RANSAC"
328
+ )
329
+ if log_path is not None:
330
+ img_keypoints_path: Path = log_path / f"img_keypoints_{postfix}.png"
331
+ img_matches_raw_path: Path = (
332
+ log_path / f"img_matches_raw_{postfix}.png"
333
+ )
334
+ img_matches_ransac_path: Path = (
335
+ log_path / f"img_matches_ransac_{postfix}.png"
336
+ )
337
+ cv2.imwrite(
338
+ str(img_keypoints_path),
339
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
340
+ )
341
+ cv2.imwrite(
342
+ str(img_matches_raw_path),
343
+ output_matches_raw[:, :, ::-1].copy(), # RGB -> BGR
344
+ )
345
+ cv2.imwrite(
346
+ str(img_matches_ransac_path),
347
+ output_matches_ransac[:, :, ::-1].copy(), # RGB -> BGR
348
+ )
349
+ plt.close("all")
350
+
351
+
352
+ class ImageMatchingService:
353
+ def __init__(self, conf: dict, device: str):
354
+ self.conf = conf
355
+ self.api = ImageMatchingAPI(conf=conf, device=device)
356
+ self.app = FastAPI()
357
+ self.register_routes()
358
+
359
+ def register_routes(self):
360
+
361
+ @self.app.get("/version")
362
+ async def version():
363
+ return {"version": get_version()}
364
+
365
+ @self.app.post("/v1/match")
366
+ async def match(
367
+ image0: UploadFile = File(...), image1: UploadFile = File(...)
368
+ ):
369
+ """
370
+ Handle the image matching request and return the processed result.
371
+
372
+ Args:
373
+ image0 (UploadFile): The first image file for matching.
374
+ image1 (UploadFile): The second image file for matching.
375
+
376
+ Returns:
377
+ JSONResponse: A JSON response containing the filtered match results
378
+ or an error message in case of failure.
379
+ """
380
+ try:
381
+ # Load the images from the uploaded files
382
+ image0_array = self.load_image(image0)
383
+ image1_array = self.load_image(image1)
384
+
385
+ # Perform image matching using the API
386
+ output = self.api(image0_array, image1_array)
387
+
388
+ # Keys to skip in the output
389
+ skip_keys = ["image0_orig", "image1_orig"]
390
+
391
+ # Postprocess the output to filter unwanted data
392
+ pred = self.postprocess(output, skip_keys)
393
+
394
+ # Return the filtered prediction as a JSON response
395
+ return JSONResponse(content=pred)
396
+ except Exception as e:
397
+ # Return an error message with status code 500 in case of exception
398
+ return JSONResponse(content={"error": str(e)}, status_code=500)
399
+
400
+ @self.app.post("/v1/extract")
401
+ async def extract(input_info: ImagesInput):
402
+ """
403
+ Extract keypoints and descriptors from images.
404
+
405
+ Args:
406
+ input_info: An object containing the image data and options.
407
+
408
+ Returns:
409
+ A list of dictionaries containing the keypoints and descriptors.
410
+ """
411
+ try:
412
+ preds = []
413
+ for i, input_image in enumerate(input_info.data):
414
+ # Load the image from the input data
415
+ image_array = to_base64_nparray(input_image)
416
+ # Extract keypoints and descriptors
417
+ output = self.api.extract(
418
+ image_array,
419
+ max_keypoints=input_info.max_keypoints[i],
420
+ binarize=input_info.binarize,
421
+ )
422
+ # Do not return the original image and image_orig
423
+ # skip_keys = ["image", "image_orig"]
424
+ skip_keys = []
425
+
426
+ # Postprocess the output
427
+ pred = self.postprocess(output, skip_keys)
428
+ preds.append(pred)
429
+ # Return the list of extracted features
430
+ return JSONResponse(content=preds)
431
+ except Exception as e:
432
+ # Return an error message if an exception occurs
433
+ return JSONResponse(content={"error": str(e)}, status_code=500)
434
+
435
+ def load_image(self, file_path: Union[str, UploadFile]) -> np.ndarray:
436
+ """
437
+ Reads an image from a file path or an UploadFile object.
438
+
439
+ Args:
440
+ file_path: A file path or an UploadFile object.
441
+
442
+ Returns:
443
+ A numpy array representing the image.
444
+ """
445
+ if isinstance(file_path, str):
446
+ file_path = Path(file_path).resolve(strict=False)
447
+ else:
448
+ file_path = file_path.file
449
+ with Image.open(file_path) as img:
450
+ image_array = np.array(img)
451
+ return image_array
452
+
453
+ def postprocess(
454
+ self, output: dict, skip_keys: list, binarize: bool = True
455
+ ) -> dict:
456
+ pred = {}
457
+ for key, value in output.items():
458
+ if key in skip_keys:
459
+ continue
460
+ if isinstance(value, np.ndarray):
461
+ pred[key] = value.tolist()
462
+ return pred
463
+
464
+ def run(self, host: str = "0.0.0.0", port: int = 8001):
465
+ uvicorn.run(self.app, host=host, port=port)
466
+
467
+
468
+ if __name__ == "__main__":
469
+ conf = {
470
+ "feature": {
471
+ "output": "feats-superpoint-n4096-rmax1600",
472
+ "model": {
473
+ "name": "superpoint",
474
+ "nms_radius": 3,
475
+ "max_keypoints": 4096,
476
+ "keypoint_threshold": 0.005,
477
+ },
478
+ "preprocessing": {
479
+ "grayscale": True,
480
+ "force_resize": True,
481
+ "resize_max": 1600,
482
+ "width": 640,
483
+ "height": 480,
484
+ "dfactor": 8,
485
+ },
486
+ },
487
+ "matcher": {
488
+ "output": "matches-NN-mutual",
489
+ "model": {
490
+ "name": "nearest_neighbor",
491
+ "do_mutual_check": True,
492
+ "match_threshold": 0.2,
493
+ },
494
+ },
495
+ "dense": False,
496
+ }
497
+
498
+ service = ImageMatchingService(conf=conf, device=DEVICE)
499
+ service.run()
api/test/CMakeLists.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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} ${OpenCV_INCLUDE_DIRS})
15
+
16
+ target_link_libraries(client PRIVATE curl jsoncpp b64 ${OpenCV_LIBS})
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 ..
api/test/client.cpp ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <curl/curl.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "helper.h"
4
+
5
+ int main() {
6
+ std::string img_path = "../../../datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot45.jpg";
7
+ cv::Mat original_img = cv::imread(img_path, cv::IMREAD_GRAYSCALE);
8
+
9
+ if (original_img.empty()) {
10
+ throw std::runtime_error("Failed to decode image");
11
+ }
12
+
13
+ // Convert the image to Base64
14
+ std::string base64_img = image_to_base64(original_img);
15
+
16
+ // Convert the Base64 back to an image
17
+ cv::Mat decoded_img = base64_to_image(base64_img);
18
+ cv::imwrite("decoded_image.jpg", decoded_img);
19
+ cv::imwrite("original_img.jpg", original_img);
20
+
21
+ // The images should be identical
22
+ if (cv::countNonZero(original_img != decoded_img) != 0) {
23
+ std::cerr << "The images are not identical" << std::endl;
24
+ return -1;
25
+ } else {
26
+ std::cout << "The images are identical!" << std::endl;
27
+ }
28
+
29
+ // construct params
30
+ APIParams params{
31
+ .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 = {
40
+ {1.23e+2f, 1.2e+1f},
41
+ {5.0e-1f, 3.0e-1f},
42
+ {2.3e+2f, 2.2e+1f},
43
+ {6.0e-1f, 4.0e-1f}
44
+ },
45
+ .binarize = {1}
46
+ };
47
+
48
+ KeyPointResults kpts_results;
49
+
50
+ // Convert the parameters to JSON
51
+ Json::Value jsonData = paramsToJson(params);
52
+ std::string url = "http://127.0.0.1:8001/v1/extract";
53
+ Json::StreamWriterBuilder writer;
54
+ std::string output = Json::writeString(writer, jsonData);
55
+
56
+ CURL* curl;
57
+ CURLcode res;
58
+ std::string readBuffer;
59
+
60
+ curl_global_init(CURL_GLOBAL_DEFAULT);
61
+ curl = curl_easy_init();
62
+ if (curl) {
63
+ struct curl_slist* hs = NULL;
64
+ hs = curl_slist_append(hs, "Content-Type: application/json");
65
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
66
+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
67
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, output.c_str());
68
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
69
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
70
+ res = curl_easy_perform(curl);
71
+
72
+ if (res != CURLE_OK)
73
+ fprintf(stderr, "curl_easy_perform() failed: %s\n",
74
+ curl_easy_strerror(res));
75
+ else {
76
+ // std::cout << "Response from server: " << readBuffer << std::endl;
77
+ kpts_results = decode_response(readBuffer);
78
+ }
79
+ curl_easy_cleanup(curl);
80
+ }
81
+ curl_global_cleanup();
82
+
83
+ return 0;
84
+ }
api/test/helper.h ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #include <sstream>
3
+ #include <fstream>
4
+ #include <vector>
5
+ #include <b64/encode.h>
6
+ #include <jsoncpp/json/json.h>
7
+ #include <opencv2/opencv.hpp>
8
+
9
+ // base64 to image
10
+ #include <boost/archive/iterators/binary_from_base64.hpp>
11
+ #include <boost/archive/iterators/transform_width.hpp>
12
+ #include <boost/archive/iterators/base64_from_binary.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
+ * @brief Constructor.
58
+ *
59
+ * @param kp The keypoints for each image.
60
+ */
61
+ KeyPointResults(const std::vector<std::vector<cv::KeyPoint>>& kp,
62
+ const std::vector<cv::Mat>& desc)
63
+ : keypoints(kp), descriptors(desc) {}
64
+
65
+ /**
66
+ * @brief Append keypoints to the result.
67
+ *
68
+ * @param kpts The keypoints to append.
69
+ */
70
+ inline void append_keypoints(std::vector<cv::KeyPoint>& kpts) {
71
+ keypoints.emplace_back(kpts);
72
+ }
73
+
74
+ /**
75
+ * @brief Append descriptors to the result.
76
+ *
77
+ * @param desc The descriptors to append.
78
+ */
79
+ inline void append_descriptors(cv::Mat& desc) {
80
+ descriptors.emplace_back(desc);
81
+ }
82
+
83
+ /**
84
+ * @brief Get the keypoints.
85
+ *
86
+ * @return The keypoints.
87
+ */
88
+ inline std::vector<std::vector<cv::KeyPoint>> get_keypoints() {
89
+ return keypoints;
90
+ }
91
+
92
+ /**
93
+ * @brief Get the descriptors.
94
+ *
95
+ * @return The descriptors.
96
+ */
97
+ inline std::vector<cv::Mat> get_descriptors() {
98
+ return descriptors;
99
+ }
100
+
101
+ private:
102
+ std::vector<std::vector<cv::KeyPoint>> keypoints;
103
+ std::vector<cv::Mat> descriptors;
104
+ std::vector<std::vector<float>> scores;
105
+ };
106
+
107
+
108
+ /**
109
+ * @brief Decodes a base64 encoded string.
110
+ *
111
+ * @param base64 The base64 encoded string to decode.
112
+ * @return The decoded string.
113
+ */
114
+ std::string base64_decode(const std::string& base64) {
115
+ using namespace boost::archive::iterators;
116
+ using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
117
+
118
+ // Find the position of the last non-whitespace character
119
+ auto end = base64.find_last_not_of(" \t\n\r");
120
+ if (end != std::string::npos) {
121
+ // Move one past the last non-whitespace character
122
+ end += 1;
123
+ }
124
+
125
+ // Decode the base64 string and return the result
126
+ return std::string(It(base64.begin()), It(base64.begin() + end));
127
+ }
128
+
129
+
130
+
131
+ /**
132
+ * @brief Decodes a base64 string into an OpenCV image
133
+ *
134
+ * @param base64 The base64 encoded string
135
+ * @return The decoded OpenCV image
136
+ */
137
+ cv::Mat base64_to_image(const std::string& base64) {
138
+ // Decode the base64 string
139
+ std::string decodedStr = base64_decode(base64);
140
+
141
+ // Decode the image
142
+ std::vector<uchar> data(decodedStr.begin(), decodedStr.end());
143
+ cv::Mat img = cv::imdecode(data, cv::IMREAD_GRAYSCALE);
144
+
145
+ // Check for errors
146
+ if (img.empty()) {
147
+ throw std::runtime_error("Failed to decode image");
148
+ }
149
+
150
+ return img;
151
+ }
152
+
153
+
154
+ /**
155
+ * @brief Encodes an OpenCV image into a base64 string
156
+ *
157
+ * This function takes an OpenCV image and encodes it into a base64 string.
158
+ * The image is first encoded as a PNG image, and then the resulting
159
+ * bytes are encoded as a base64 string.
160
+ *
161
+ * @param img The OpenCV image
162
+ * @return The base64 encoded string
163
+ *
164
+ * @throws std::runtime_error if the image is empty or encoding fails
165
+ */
166
+ std::string image_to_base64(cv::Mat &img) {
167
+ if (img.empty()) {
168
+ throw std::runtime_error("Failed to read image");
169
+ }
170
+
171
+ // Encode the image as a PNG
172
+ std::vector<uchar> buf;
173
+ if (!cv::imencode(".png", img, buf)) {
174
+ throw std::runtime_error("Failed to encode image");
175
+ }
176
+
177
+ // Encode the bytes as a base64 string
178
+ using namespace boost::archive::iterators;
179
+ using It = base64_from_binary<transform_width<std::vector<uchar>::const_iterator, 6, 8>>;
180
+ std::string base64(It(buf.begin()), It(buf.end()));
181
+
182
+ // Pad the string with '=' characters to a multiple of 4 bytes
183
+ base64.append((3 - buf.size() % 3) % 3, '=');
184
+
185
+ return base64;
186
+ }
187
+
188
+
189
+ /**
190
+ * @brief Callback function for libcurl to write data to a string
191
+ *
192
+ * This function is used as a callback for libcurl to write data to a string.
193
+ * It takes the contents, size, and nmemb as parameters, and writes the data to
194
+ * the string.
195
+ *
196
+ * @param contents The data to write
197
+ * @param size The size of the data
198
+ * @param nmemb The number of members in the data
199
+ * @param s The string to write the data to
200
+ * @return The number of bytes written
201
+ */
202
+ size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s) {
203
+ size_t newLength = size * nmemb;
204
+ try {
205
+ // Resize the string to fit the new data
206
+ s->resize(s->size() + newLength);
207
+ } catch (std::bad_alloc& e) {
208
+ // If there's an error allocating memory, return 0
209
+ return 0;
210
+ }
211
+
212
+ // Copy the data to the string
213
+ std::copy(static_cast<const char*>(contents),
214
+ static_cast<const char*>(contents) + newLength,
215
+ s->begin() + s->size() - newLength);
216
+ return newLength;
217
+ }
218
+
219
+ // Helper functions
220
+
221
+ /**
222
+ * @brief Helper function to convert a type to a Json::Value
223
+ *
224
+ * This function takes a value of type T and converts it to a Json::Value.
225
+ * It is used to simplify the process of converting a type to a Json::Value.
226
+ *
227
+ * @param val The value to convert
228
+ * @return The converted Json::Value
229
+ */
230
+ template <typename T>
231
+ Json::Value toJson(const T& val) {
232
+ return Json::Value(val);
233
+ }
234
+
235
+ /**
236
+ * @brief Converts a vector to a Json::Value
237
+ *
238
+ * This function takes a vector of type T and converts it to a Json::Value.
239
+ * Each element in the vector is appended to the Json::Value array.
240
+ *
241
+ * @param vec The vector to convert to Json::Value
242
+ * @return The Json::Value representing the vector
243
+ */
244
+ template <typename T>
245
+ Json::Value vectorToJson(const std::vector<T>& vec) {
246
+ Json::Value json(Json::arrayValue);
247
+ for (const auto& item : vec) {
248
+ json.append(item);
249
+ }
250
+ return json;
251
+ }
252
+
253
+ /**
254
+ * @brief Converts a nested vector to a Json::Value
255
+ *
256
+ * This function takes a nested vector of type T and converts it to a Json::Value.
257
+ * Each sub-vector is converted to a Json::Value array and appended to the main Json::Value array.
258
+ *
259
+ * @param vec The nested vector to convert to Json::Value
260
+ * @return The Json::Value representing the nested vector
261
+ */
262
+ template <typename T>
263
+ Json::Value nestedVectorToJson(const std::vector<std::vector<T>>& vec) {
264
+ Json::Value json(Json::arrayValue);
265
+ for (const auto& subVec : vec) {
266
+ json.append(vectorToJson(subVec));
267
+ }
268
+ return json;
269
+ }
270
+
271
+
272
+
273
+ /**
274
+ * @brief Converts the APIParams struct to a Json::Value
275
+ *
276
+ * This function takes an APIParams struct and converts it to a Json::Value.
277
+ * The Json::Value is a JSON object with the following fields:
278
+ * - data: a JSON array of base64 encoded images
279
+ * - max_keypoints: a JSON array of integers, max number of keypoints for each image
280
+ * - timestamps: a JSON array of timestamps, one for each image
281
+ * - grayscale: a JSON boolean, whether to convert images to grayscale
282
+ * - image_hw: a nested JSON array, each sub-array contains the height and width of an image
283
+ * - feature_type: a JSON integer, the type of feature detector to use
284
+ * - rotates: a JSON array of doubles, the rotation of each image
285
+ * - scales: a JSON array of doubles, the scale of each image
286
+ * - reference_points: a nested JSON array, each sub-array contains the reference points of an image
287
+ * - binarize: a JSON boolean, whether to binarize the descriptors
288
+ *
289
+ * @param params The APIParams struct to convert
290
+ * @return The Json::Value representing the APIParams struct
291
+ */
292
+ Json::Value paramsToJson(const APIParams& params) {
293
+ Json::Value json;
294
+ json["data"] = vectorToJson(params.data);
295
+ json["max_keypoints"] = vectorToJson(params.max_keypoints);
296
+ json["timestamps"] = vectorToJson(params.timestamps);
297
+ json["grayscale"] = toJson(params.grayscale);
298
+ json["image_hw"] = nestedVectorToJson(params.image_hw);
299
+ json["feature_type"] = toJson(params.feature_type);
300
+ json["rotates"] = vectorToJson(params.rotates);
301
+ json["scales"] = vectorToJson(params.scales);
302
+ json["reference_points"] = nestedVectorToJson(params.reference_points);
303
+ json["binarize"] = toJson(params.binarize);
304
+ return json;
305
+ }
306
+
307
+ template<typename T>
308
+ cv::Mat jsonToMat(Json::Value json) {
309
+ int rows = json.size();
310
+ int cols = json[0].size();
311
+
312
+ // Create a single array to hold all the data.
313
+ std::vector<T> data;
314
+ data.reserve(rows * cols);
315
+
316
+ for (int i = 0; i < rows; i++) {
317
+ for (int j = 0; j < cols; j++) {
318
+ data.push_back(static_cast<T>(json[i][j].asInt()));
319
+ }
320
+ }
321
+
322
+ // Create a cv::Mat object that points to the data.
323
+ cv::Mat mat(rows, cols, CV_8UC1, data.data()); // Change the type if necessary.
324
+ // cv::Mat mat(cols, rows,CV_8UC1, data.data()); // Change the type if necessary.
325
+
326
+ return mat;
327
+ }
328
+
329
+
330
+
331
+ /**
332
+ * @brief Decodes the response of the server and prints the keypoints
333
+ *
334
+ * This function takes the response of the server, a JSON string, and decodes
335
+ * it. It then prints the keypoints and draws them on the original image.
336
+ *
337
+ * @param response The response of the server
338
+ * @return The keypoints and descriptors
339
+ */
340
+ KeyPointResults decode_response(const std::string& response, bool viz=true) {
341
+ Json::CharReaderBuilder builder;
342
+ Json::CharReader* reader = builder.newCharReader();
343
+
344
+ Json::Value jsonData;
345
+ std::string errors;
346
+
347
+ // Parse the JSON response
348
+ bool parsingSuccessful = reader->parse(response.c_str(),
349
+ response.c_str() + response.size(), &jsonData, &errors);
350
+ delete reader;
351
+
352
+ if (!parsingSuccessful) {
353
+ // Handle error
354
+ std::cout << "Failed to parse the JSON, errors:" << std::endl;
355
+ std::cout << errors << std::endl;
356
+ return KeyPointResults();
357
+ }
358
+
359
+ KeyPointResults kpts_results;
360
+
361
+ // Iterate over the images
362
+ for (const auto& jsonItem : jsonData) {
363
+ auto jkeypoints = jsonItem["keypoints"];
364
+ auto jkeypoints_orig = jsonItem["keypoints_orig"];
365
+ auto jdescriptors = jsonItem["descriptors"];
366
+ auto jscores = jsonItem["scores"];
367
+ auto jimageSize = jsonItem["image_size"];
368
+ auto joriginalSize = jsonItem["original_size"];
369
+ auto jsize = jsonItem["size"];
370
+
371
+ std::vector<cv::KeyPoint> vkeypoints;
372
+ std::vector<float> vscores;
373
+
374
+ // Iterate over the keypoints
375
+ int counter = 0;
376
+ for (const auto& keypoint : jkeypoints_orig) {
377
+ if (counter < 10) {
378
+ // Print the first 10 keypoints
379
+ std::cout << keypoint[0].asFloat() << ", "
380
+ << keypoint[1].asFloat() << std::endl;
381
+ }
382
+ counter++;
383
+ // Convert the Json::Value to a cv::KeyPoint
384
+ vkeypoints.emplace_back(cv::KeyPoint(keypoint[0].asFloat(),
385
+ keypoint[1].asFloat(), 0.0));
386
+ }
387
+
388
+ if (viz && jsonItem.isMember("image_orig")) {
389
+
390
+ auto jimg_orig = jsonItem["image_orig"];
391
+ cv::Mat img = jsonToMat<uchar>(jimg_orig);
392
+ cv::imwrite("viz_image_orig.jpg", img);
393
+
394
+ // Draw keypoints on the image
395
+ cv::Mat imgWithKeypoints;
396
+ cv::drawKeypoints(img, vkeypoints,
397
+ imgWithKeypoints, cv::Scalar(0, 0, 255));
398
+
399
+ // Write the image with keypoints
400
+ std::string filename = "viz_image_orig_keypoints.jpg";
401
+ cv::imwrite(filename, imgWithKeypoints);
402
+ }
403
+
404
+ // Iterate over the descriptors
405
+ cv::Mat descriptors = jsonToMat<uchar>(jdescriptors);
406
+ kpts_results.append_keypoints(vkeypoints);
407
+ kpts_results.append_descriptors(descriptors);
408
+ }
409
+ return kpts_results;
410
+ }
api/types.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class ImagesInput(BaseModel):
7
+ data: List[str] = []
8
+ max_keypoints: List[int] = []
9
+ timestamps: List[str] = []
10
+ grayscale: bool = False
11
+ image_hw: List[List[int]] = [[], []]
12
+ feature_type: int = 0
13
+ rotates: List[float] = []
14
+ scales: List[float] = []
15
+ reference_points: List[List[float]] = []
16
+ binarize: bool = False
app.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ from ui.app_class import ImageMatchingApp
4
+
5
+ if __name__ == "__main__":
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument(
8
+ "--server_name",
9
+ type=str,
10
+ default="0.0.0.0",
11
+ help="server name",
12
+ )
13
+ parser.add_argument(
14
+ "--server_port",
15
+ type=int,
16
+ default=7860,
17
+ help="server port",
18
+ )
19
+ parser.add_argument(
20
+ "--config",
21
+ type=str,
22
+ default=Path(__file__).parent / "ui/config.yaml",
23
+ help="config file",
24
+ )
25
+ args = parser.parse_args()
26
+ ImageMatchingApp(
27
+ args.server_name, args.server_port, config=args.config
28
+ ).run()
build_docker.sh 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/Dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official conda-based Python image as a parent image
2
+ FROM pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime
3
+ LABEL maintainer vincentqyw
4
+ ARG PYTHON_VERSION=3.10.10
5
+
6
+ # Set the working directory to /code
7
+ WORKDIR /code
8
+
9
+ # Install Git and Git LFS
10
+ RUN apt-get update && apt-get install -y git-lfs
11
+ RUN git lfs install
12
+
13
+ # Clone the Git repository
14
+ RUN git clone https://huggingface.co/spaces/Realcat/image-matching-webui /code
15
+
16
+ RUN conda create -n imw python=${PYTHON_VERSION}
17
+ RUN echo "source activate imw" > ~/.bashrc
18
+ ENV PATH /opt/conda/envs/imw/bin:$PATH
19
+
20
+ # Make RUN commands use the new environment
21
+ SHELL ["conda", "run", "-n", "imw", "/bin/bash", "-c"]
22
+ RUN pip install --upgrade pip
23
+ RUN pip install -r requirements.txt
24
+ RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
25
+
26
+ # Export port
27
+ EXPOSE 7860
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
format.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ python -m flake8 ui/*.py api/*.py hloc/*.py hloc/matchers/*.py hloc/extractors/*.py
2
+ python -m isort ui/*.py api/*.py hloc/*.py hloc/matchers/*.py hloc/extractors/*.py
3
+ python -m black ui/*.py api/*.py hloc/*.py hloc/matchers/*.py hloc/extractors/*.py
hloc/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
hloc/colmap_from_nvm.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
29
+ f"Found {len(images)} images and {len(cameras)} cameras in database."
30
+ )
31
+ return images, cameras
32
+
33
+
34
+ def quaternion_to_rotation_matrix(qvec):
35
+ qvec = qvec / np.linalg.norm(qvec)
36
+ w, x, y, z = qvec
37
+ R = np.array(
38
+ [
39
+ [
40
+ 1 - 2 * y * y - 2 * z * z,
41
+ 2 * x * y - 2 * z * w,
42
+ 2 * x * z + 2 * y * w,
43
+ ],
44
+ [
45
+ 2 * x * y + 2 * z * w,
46
+ 1 - 2 * x * x - 2 * z * z,
47
+ 2 * y * z - 2 * x * w,
48
+ ],
49
+ [
50
+ 2 * x * z - 2 * y * w,
51
+ 2 * y * z + 2 * x * w,
52
+ 1 - 2 * x * x - 2 * y * y,
53
+ ],
54
+ ]
55
+ )
56
+ return R
57
+
58
+
59
+ def camera_center_to_translation(c, qvec):
60
+ R = quaternion_to_rotation_matrix(qvec)
61
+ return (-1) * np.matmul(R, c)
62
+
63
+
64
+ def read_nvm_model(
65
+ nvm_path, intrinsics_path, image_ids, camera_ids, skip_points=False
66
+ ):
67
+ with open(intrinsics_path, "r") as f:
68
+ raw_intrinsics = f.readlines()
69
+
70
+ logger.info(f"Reading {len(raw_intrinsics)} cameras...")
71
+ cameras = {}
72
+ for intrinsics in raw_intrinsics:
73
+ intrinsics = intrinsics.strip("\n").split(" ")
74
+ name, camera_model, width, height = intrinsics[:4]
75
+ params = [float(p) for p in intrinsics[4:]]
76
+ camera_model = CAMERA_MODEL_NAMES[camera_model]
77
+ assert len(params) == camera_model.num_params
78
+ camera_id = camera_ids[name]
79
+ camera = Camera(
80
+ id=camera_id,
81
+ model=camera_model.model_name,
82
+ width=int(width),
83
+ height=int(height),
84
+ params=params,
85
+ )
86
+ cameras[camera_id] = camera
87
+
88
+ nvm_f = open(nvm_path, "r")
89
+ line = nvm_f.readline()
90
+ while line == "\n" or line.startswith("NVM_V3"):
91
+ line = nvm_f.readline()
92
+ num_images = int(line)
93
+ assert num_images == len(cameras)
94
+
95
+ logger.info(f"Reading {num_images} images...")
96
+ image_idx_to_db_image_id = []
97
+ image_data = []
98
+ i = 0
99
+ while i < num_images:
100
+ line = nvm_f.readline()
101
+ if line == "\n":
102
+ continue
103
+ data = line.strip("\n").split(" ")
104
+ image_data.append(data)
105
+ image_idx_to_db_image_id.append(image_ids[data[0]])
106
+ i += 1
107
+
108
+ line = nvm_f.readline()
109
+ while line == "\n":
110
+ line = nvm_f.readline()
111
+ num_points = int(line)
112
+
113
+ if skip_points:
114
+ logger.info(f"Skipping {num_points} points.")
115
+ num_points = 0
116
+ else:
117
+ logger.info(f"Reading {num_points} points...")
118
+ points3D = {}
119
+ image_idx_to_keypoints = defaultdict(list)
120
+ i = 0
121
+ pbar = tqdm(total=num_points, unit="pts")
122
+ while i < num_points:
123
+ line = nvm_f.readline()
124
+ if line == "\n":
125
+ continue
126
+
127
+ data = line.strip("\n").split(" ")
128
+ x, y, z, r, g, b, num_observations = data[:7]
129
+ obs_image_ids, point2D_idxs = [], []
130
+ for j in range(int(num_observations)):
131
+ s = 7 + 4 * j
132
+ img_index, kp_index, kx, ky = data[s : s + 4]
133
+ image_idx_to_keypoints[int(img_index)].append(
134
+ (int(kp_index), float(kx), float(ky), i)
135
+ )
136
+ db_image_id = image_idx_to_db_image_id[int(img_index)]
137
+ obs_image_ids.append(db_image_id)
138
+ point2D_idxs.append(kp_index)
139
+
140
+ point = Point3D(
141
+ id=i,
142
+ xyz=np.array([x, y, z], float),
143
+ rgb=np.array([r, g, b], int),
144
+ error=1.0, # fake
145
+ image_ids=np.array(obs_image_ids, int),
146
+ point2D_idxs=np.array(point2D_idxs, int),
147
+ )
148
+ points3D[i] = point
149
+
150
+ i += 1
151
+ pbar.update(1)
152
+ pbar.close()
153
+
154
+ logger.info("Parsing image data...")
155
+ images = {}
156
+ for i, data in enumerate(image_data):
157
+ # Skip the focal length. Skip the distortion and terminal 0.
158
+ name, _, qw, qx, qy, qz, cx, cy, cz, _, _ = data
159
+ qvec = np.array([qw, qx, qy, qz], float)
160
+ c = np.array([cx, cy, cz], float)
161
+ t = camera_center_to_translation(c, qvec)
162
+
163
+ if i in image_idx_to_keypoints:
164
+ # NVM only stores triangulated 2D keypoints: add dummy ones
165
+ keypoints = image_idx_to_keypoints[i]
166
+ point2D_idxs = np.array([d[0] for d in keypoints])
167
+ tri_xys = np.array([[x, y] for _, x, y, _ in keypoints])
168
+ tri_ids = np.array([i for _, _, _, i in keypoints])
169
+
170
+ num_2Dpoints = max(point2D_idxs) + 1
171
+ xys = np.zeros((num_2Dpoints, 2), float)
172
+ point3D_ids = np.full(num_2Dpoints, -1, int)
173
+ xys[point2D_idxs] = tri_xys
174
+ point3D_ids[point2D_idxs] = tri_ids
175
+ else:
176
+ xys = np.zeros((0, 2), float)
177
+ point3D_ids = np.full(0, -1, int)
178
+
179
+ image_id = image_ids[name]
180
+ image = Image(
181
+ id=image_id,
182
+ qvec=qvec,
183
+ tvec=t,
184
+ camera_id=camera_ids[name],
185
+ name=name,
186
+ xys=xys,
187
+ point3D_ids=point3D_ids,
188
+ )
189
+ images[image_id] = image
190
+
191
+ return cameras, images, points3D
192
+
193
+
194
+ def main(nvm, intrinsics, database, output, skip_points=False):
195
+ assert nvm.exists(), nvm
196
+ assert intrinsics.exists(), intrinsics
197
+ assert database.exists(), database
198
+
199
+ image_ids, camera_ids = recover_database_images_and_ids(database)
200
+
201
+ logger.info("Reading the NVM model...")
202
+ model = read_nvm_model(
203
+ nvm, intrinsics, image_ids, camera_ids, skip_points=skip_points
204
+ )
205
+
206
+ logger.info("Writing the COLMAP model...")
207
+ output.mkdir(exist_ok=True, parents=True)
208
+ write_model(*model, path=str(output), ext=".bin")
209
+ logger.info("Done.")
210
+
211
+
212
+ if __name__ == "__main__":
213
+ parser = argparse.ArgumentParser()
214
+ parser.add_argument("--nvm", required=True, type=Path)
215
+ parser.add_argument("--intrinsics", required=True, type=Path)
216
+ parser.add_argument("--database", required=True, type=Path)
217
+ parser.add_argument("--output", required=True, type=Path)
218
+ parser.add_argument("--skip_points", action="store_true")
219
+ args = parser.parse_args()
220
+ main(**args.__dict__)
hloc/extract_features.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "force_resize": True,
77
+ "width": 640,
78
+ "height": 480,
79
+ "dfactor": 8,
80
+ },
81
+ },
82
+ "r2d2": {
83
+ "output": "feats-r2d2-n5000-r1024",
84
+ "model": {
85
+ "name": "r2d2",
86
+ "max_keypoints": 5000,
87
+ "reliability_threshold": 0.7,
88
+ "repetability_threshold": 0.7,
89
+ },
90
+ "preprocessing": {
91
+ "grayscale": False,
92
+ "force_resize": True,
93
+ "resize_max": 1024,
94
+ "width": 640,
95
+ "height": 480,
96
+ "dfactor": 8,
97
+ },
98
+ },
99
+ "d2net-ss": {
100
+ "output": "feats-d2net-ss-n5000-r1600",
101
+ "model": {
102
+ "name": "d2net",
103
+ "multiscale": False,
104
+ "max_keypoints": 5000,
105
+ },
106
+ "preprocessing": {
107
+ "grayscale": False,
108
+ "resize_max": 1600,
109
+ "force_resize": True,
110
+ "width": 640,
111
+ "height": 480,
112
+ "dfactor": 8,
113
+ },
114
+ },
115
+ "d2net-ms": {
116
+ "output": "feats-d2net-ms-n5000-r1600",
117
+ "model": {
118
+ "name": "d2net",
119
+ "multiscale": True,
120
+ "max_keypoints": 5000,
121
+ },
122
+ "preprocessing": {
123
+ "grayscale": False,
124
+ "resize_max": 1600,
125
+ "force_resize": True,
126
+ "width": 640,
127
+ "height": 480,
128
+ "dfactor": 8,
129
+ },
130
+ },
131
+ "rord": {
132
+ "output": "feats-rord-ss-n5000-r1600",
133
+ "model": {
134
+ "name": "rord",
135
+ "multiscale": False,
136
+ "max_keypoints": 5000,
137
+ },
138
+ "preprocessing": {
139
+ "grayscale": False,
140
+ "resize_max": 1600,
141
+ "force_resize": True,
142
+ "width": 640,
143
+ "height": 480,
144
+ "dfactor": 8,
145
+ },
146
+ },
147
+ "rootsift": {
148
+ "output": "feats-rootsift-n5000-r1600",
149
+ "model": {
150
+ "name": "dog",
151
+ "descriptor": "rootsift",
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
+ "sift": {
164
+ "output": "feats-sift-n5000-r1600",
165
+ "model": {
166
+ "name": "sift",
167
+ "rootsift": True,
168
+ "max_keypoints": 5000,
169
+ },
170
+ "preprocessing": {
171
+ "grayscale": True,
172
+ "force_resize": True,
173
+ "resize_max": 1600,
174
+ "width": 640,
175
+ "height": 480,
176
+ "dfactor": 8,
177
+ },
178
+ },
179
+ "sosnet": {
180
+ "output": "feats-sosnet-n5000-r1600",
181
+ "model": {
182
+ "name": "dog",
183
+ "descriptor": "sosnet",
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
+ "hardnet": {
196
+ "output": "feats-hardnet-n5000-r1600",
197
+ "model": {
198
+ "name": "dog",
199
+ "descriptor": "hardnet",
200
+ "max_keypoints": 5000,
201
+ },
202
+ "preprocessing": {
203
+ "grayscale": True,
204
+ "resize_max": 1600,
205
+ "force_resize": True,
206
+ "width": 640,
207
+ "height": 480,
208
+ "dfactor": 8,
209
+ },
210
+ },
211
+ "disk": {
212
+ "output": "feats-disk-n5000-r1600",
213
+ "model": {
214
+ "name": "disk",
215
+ "max_keypoints": 5000,
216
+ },
217
+ "preprocessing": {
218
+ "grayscale": False,
219
+ "resize_max": 1600,
220
+ "force_resize": True,
221
+ "width": 640,
222
+ "height": 480,
223
+ "dfactor": 8,
224
+ },
225
+ },
226
+ "xfeat": {
227
+ "output": "feats-xfeat-n5000-r1600",
228
+ "model": {
229
+ "name": "xfeat",
230
+ "max_keypoints": 5000,
231
+ },
232
+ "preprocessing": {
233
+ "grayscale": False,
234
+ "resize_max": 1600,
235
+ "force_resize": True,
236
+ "width": 640,
237
+ "height": 480,
238
+ "dfactor": 8,
239
+ },
240
+ },
241
+ "alike": {
242
+ "output": "feats-alike-n5000-r1600",
243
+ "model": {
244
+ "name": "alike",
245
+ "max_keypoints": 5000,
246
+ "use_relu": True,
247
+ "multiscale": False,
248
+ "detection_threshold": 0.5,
249
+ "top_k": -1,
250
+ "sub_pixel": False,
251
+ },
252
+ "preprocessing": {
253
+ "grayscale": False,
254
+ "resize_max": 1600,
255
+ "force_resize": True,
256
+ "width": 640,
257
+ "height": 480,
258
+ "dfactor": 8,
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
+ "force_resize": True,
272
+ "width": 640,
273
+ "height": 480,
274
+ "dfactor": 8,
275
+ },
276
+ },
277
+ "darkfeat": {
278
+ "output": "feats-darkfeat-n5000-r1600",
279
+ "model": {
280
+ "name": "darkfeat",
281
+ "max_keypoints": 5000,
282
+ "reliability_threshold": 0.7,
283
+ "repetability_threshold": 0.7,
284
+ },
285
+ "preprocessing": {
286
+ "grayscale": False,
287
+ "force_resize": True,
288
+ "resize_max": 1600,
289
+ "width": 640,
290
+ "height": 480,
291
+ "dfactor": 8,
292
+ },
293
+ },
294
+ "dedode": {
295
+ "output": "feats-dedode-n5000-r1600",
296
+ "model": {
297
+ "name": "dedode",
298
+ "max_keypoints": 5000,
299
+ },
300
+ "preprocessing": {
301
+ "grayscale": False,
302
+ "force_resize": True,
303
+ "resize_max": 1600,
304
+ "width": 768,
305
+ "height": 768,
306
+ "dfactor": 8,
307
+ },
308
+ },
309
+ "example": {
310
+ "output": "feats-example-n2000-r1024",
311
+ "model": {
312
+ "name": "example",
313
+ "keypoint_threshold": 0.1,
314
+ "max_keypoints": 2000,
315
+ "model_name": "model.pth",
316
+ },
317
+ "preprocessing": {
318
+ "grayscale": False,
319
+ "force_resize": True,
320
+ "resize_max": 1024,
321
+ "width": 768,
322
+ "height": 768,
323
+ "dfactor": 8,
324
+ },
325
+ },
326
+ "sfd2": {
327
+ "output": "feats-sfd2-n4096-r1600",
328
+ "model": {
329
+ "name": "sfd2",
330
+ "max_keypoints": 4096,
331
+ },
332
+ "preprocessing": {
333
+ "grayscale": False,
334
+ "force_resize": True,
335
+ "resize_max": 1600,
336
+ "width": 640,
337
+ "height": 480,
338
+ "conf_th": 0.001,
339
+ "multiscale": False,
340
+ "scales": [1.0],
341
+ },
342
+ },
343
+ # Global descriptors
344
+ "dir": {
345
+ "output": "global-feats-dir",
346
+ "model": {"name": "dir"},
347
+ "preprocessing": {"resize_max": 1024},
348
+ },
349
+ "netvlad": {
350
+ "output": "global-feats-netvlad",
351
+ "model": {"name": "netvlad"},
352
+ "preprocessing": {"resize_max": 1024},
353
+ },
354
+ "openibl": {
355
+ "output": "global-feats-openibl",
356
+ "model": {"name": "openibl"},
357
+ "preprocessing": {"resize_max": 1024},
358
+ },
359
+ "cosplace": {
360
+ "output": "global-feats-cosplace",
361
+ "model": {"name": "cosplace"},
362
+ "preprocessing": {"resize_max": 1024},
363
+ },
364
+ "eigenplaces": {
365
+ "output": "global-feats-eigenplaces",
366
+ "model": {"name": "eigenplaces"},
367
+ "preprocessing": {"resize_max": 1024},
368
+ },
369
+ }
370
+
371
+
372
+ def resize_image(image, size, interp):
373
+ if interp.startswith("cv2_"):
374
+ interp = getattr(cv2, "INTER_" + interp[len("cv2_") :].upper())
375
+ h, w = image.shape[:2]
376
+ if interp == cv2.INTER_AREA and (w < size[0] or h < size[1]):
377
+ interp = cv2.INTER_LINEAR
378
+ resized = cv2.resize(image, size, interpolation=interp)
379
+ elif interp.startswith("pil_"):
380
+ interp = getattr(PIL.Image, interp[len("pil_") :].upper())
381
+ resized = PIL.Image.fromarray(image.astype(np.uint8))
382
+ resized = resized.resize(size, resample=interp)
383
+ resized = np.asarray(resized, dtype=image.dtype)
384
+ else:
385
+ raise ValueError(f"Unknown interpolation {interp}.")
386
+ return resized
387
+
388
+
389
+ class ImageDataset(torch.utils.data.Dataset):
390
+ default_conf = {
391
+ "globs": ["*.jpg", "*.png", "*.jpeg", "*.JPG", "*.PNG"],
392
+ "grayscale": False,
393
+ "resize_max": None,
394
+ "force_resize": False,
395
+ "interpolation": "cv2_area", # pil_linear is more accurate but slower
396
+ }
397
+
398
+ def __init__(self, root, conf, paths=None):
399
+ self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf})
400
+ self.root = root
401
+
402
+ if paths is None:
403
+ paths = []
404
+ for g in conf.globs:
405
+ paths += list(Path(root).glob("**/" + g))
406
+ if len(paths) == 0:
407
+ raise ValueError(f"Could not find any image in root: {root}.")
408
+ paths = sorted(list(set(paths)))
409
+ self.names = [i.relative_to(root).as_posix() for i in paths]
410
+ logger.info(f"Found {len(self.names)} images in root {root}.")
411
+ else:
412
+ if isinstance(paths, (Path, str)):
413
+ self.names = parse_image_lists(paths)
414
+ elif isinstance(paths, collections.Iterable):
415
+ self.names = [
416
+ p.as_posix() if isinstance(p, Path) else p for p in paths
417
+ ]
418
+ else:
419
+ raise ValueError(f"Unknown format for path argument {paths}.")
420
+
421
+ for name in self.names:
422
+ if not (root / name).exists():
423
+ raise ValueError(
424
+ f"Image {name} does not exists in root: {root}."
425
+ )
426
+
427
+ def __getitem__(self, idx):
428
+ name = self.names[idx]
429
+ image = read_image(self.root / name, self.conf.grayscale)
430
+ image = image.astype(np.float32)
431
+ size = image.shape[:2][::-1]
432
+
433
+ if self.conf.resize_max and (
434
+ self.conf.force_resize or max(size) > self.conf.resize_max
435
+ ):
436
+ scale = self.conf.resize_max / max(size)
437
+ size_new = tuple(int(round(x * scale)) for x in size)
438
+ image = resize_image(image, size_new, self.conf.interpolation)
439
+
440
+ if self.conf.grayscale:
441
+ image = image[None]
442
+ else:
443
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
444
+ image = image / 255.0
445
+
446
+ data = {
447
+ "image": image,
448
+ "original_size": np.array(size),
449
+ }
450
+ return data
451
+
452
+ def __len__(self):
453
+ return len(self.names)
454
+
455
+
456
+ def extract(model, image_0, conf):
457
+ default_conf = {
458
+ "grayscale": True,
459
+ "resize_max": 1024,
460
+ "dfactor": 8,
461
+ "cache_images": False,
462
+ "force_resize": False,
463
+ "width": 320,
464
+ "height": 240,
465
+ "interpolation": "cv2_area",
466
+ }
467
+ conf = SimpleNamespace(**{**default_conf, **conf})
468
+ device = "cuda" if torch.cuda.is_available() else "cpu"
469
+
470
+ def preprocess(image: np.ndarray, conf: SimpleNamespace):
471
+ image = image.astype(np.float32, copy=False)
472
+ size = image.shape[:2][::-1]
473
+ scale = np.array([1.0, 1.0])
474
+ if conf.resize_max:
475
+ scale = conf.resize_max / max(size)
476
+ if scale < 1.0:
477
+ size_new = tuple(int(round(x * scale)) for x in size)
478
+ image = resize_image(image, size_new, "cv2_area")
479
+ scale = np.array(size) / np.array(size_new)
480
+ if conf.force_resize:
481
+ image = resize_image(image, (conf.width, conf.height), "cv2_area")
482
+ size_new = (conf.width, conf.height)
483
+ scale = np.array(size) / np.array(size_new)
484
+ if conf.grayscale:
485
+ assert image.ndim == 2, image.shape
486
+ image = image[None]
487
+ else:
488
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
489
+ image = torch.from_numpy(image / 255.0).float()
490
+
491
+ # assure that the size is divisible by dfactor
492
+ size_new = tuple(
493
+ map(
494
+ lambda x: int(x // conf.dfactor * conf.dfactor),
495
+ image.shape[-2:],
496
+ )
497
+ )
498
+ image = F.resize(image, size=size_new, antialias=True)
499
+ input_ = image.to(device, non_blocking=True)[None]
500
+ data = {
501
+ "image": input_,
502
+ "image_orig": image_0,
503
+ "original_size": np.array(size),
504
+ "size": np.array(image.shape[1:][::-1]),
505
+ }
506
+ return data
507
+
508
+ # convert to grayscale if needed
509
+ if len(image_0.shape) == 3 and conf.grayscale:
510
+ image0 = cv2.cvtColor(image_0, cv2.COLOR_RGB2GRAY)
511
+ else:
512
+ image0 = image_0
513
+ # comment following lines, image is always RGB mode
514
+ # if not conf.grayscale and len(image_0.shape) == 3:
515
+ # image0 = image_0[:, :, ::-1] # BGR to RGB
516
+ data = preprocess(image0, conf)
517
+ pred = model({"image": data["image"]})
518
+ pred["image_size"] = data["original_size"]
519
+ pred = {**pred, **data}
520
+ return pred
521
+
522
+
523
+ @torch.no_grad()
524
+ def main(
525
+ conf: Dict,
526
+ image_dir: Path,
527
+ export_dir: Optional[Path] = None,
528
+ as_half: bool = True,
529
+ image_list: Optional[Union[Path, List[str]]] = None,
530
+ feature_path: Optional[Path] = None,
531
+ overwrite: bool = False,
532
+ ) -> Path:
533
+ logger.info(
534
+ "Extracting local features with configuration:"
535
+ f"\n{pprint.pformat(conf)}"
536
+ )
537
+
538
+ dataset = ImageDataset(image_dir, conf["preprocessing"], image_list)
539
+ if feature_path is None:
540
+ feature_path = Path(export_dir, conf["output"] + ".h5")
541
+ feature_path.parent.mkdir(exist_ok=True, parents=True)
542
+ skip_names = set(
543
+ list_h5_names(feature_path)
544
+ if feature_path.exists() and not overwrite
545
+ else ()
546
+ )
547
+ dataset.names = [n for n in dataset.names if n not in skip_names]
548
+ if len(dataset.names) == 0:
549
+ logger.info("Skipping the extraction.")
550
+ return feature_path
551
+
552
+ device = "cuda" if torch.cuda.is_available() else "cpu"
553
+ Model = dynamic_load(extractors, conf["model"]["name"])
554
+ model = Model(conf["model"]).eval().to(device)
555
+
556
+ loader = torch.utils.data.DataLoader(
557
+ dataset, num_workers=1, shuffle=False, pin_memory=True
558
+ )
559
+ for idx, data in enumerate(tqdm(loader)):
560
+ name = dataset.names[idx]
561
+ pred = model({"image": data["image"].to(device, non_blocking=True)})
562
+ pred = {k: v[0].cpu().numpy() for k, v in pred.items()}
563
+
564
+ pred["image_size"] = original_size = data["original_size"][0].numpy()
565
+ if "keypoints" in pred:
566
+ size = np.array(data["image"].shape[-2:][::-1])
567
+ scales = (original_size / size).astype(np.float32)
568
+ pred["keypoints"] = (pred["keypoints"] + 0.5) * scales[None] - 0.5
569
+ if "scales" in pred:
570
+ pred["scales"] *= scales.mean()
571
+ # add keypoint uncertainties scaled to the original resolution
572
+ uncertainty = getattr(model, "detection_noise", 1) * scales.mean()
573
+
574
+ if as_half:
575
+ for k in pred:
576
+ dt = pred[k].dtype
577
+ if (dt == np.float32) and (dt != np.float16):
578
+ pred[k] = pred[k].astype(np.float16)
579
+
580
+ with h5py.File(str(feature_path), "a", libver="latest") as fd:
581
+ try:
582
+ if name in fd:
583
+ del fd[name]
584
+ grp = fd.create_group(name)
585
+ for k, v in pred.items():
586
+ grp.create_dataset(k, data=v)
587
+ if "keypoints" in pred:
588
+ grp["keypoints"].attrs["uncertainty"] = uncertainty
589
+ except OSError as error:
590
+ if "No space left on device" in error.args[0]:
591
+ logger.error(
592
+ "Out of disk space: storing features on disk can take "
593
+ "significant space, did you enable the as_half flag?"
594
+ )
595
+ del grp, fd[name]
596
+ raise error
597
+
598
+ del pred
599
+
600
+ logger.info("Finished exporting features.")
601
+ return feature_path
602
+
603
+
604
+ if __name__ == "__main__":
605
+ parser = argparse.ArgumentParser()
606
+ parser.add_argument("--image_dir", type=Path, required=True)
607
+ parser.add_argument("--export_dir", type=Path, required=True)
608
+ parser.add_argument(
609
+ "--conf",
610
+ type=str,
611
+ default="superpoint_aachen",
612
+ choices=list(confs.keys()),
613
+ )
614
+ parser.add_argument("--as_half", action="store_true")
615
+ parser.add_argument("--image_list", type=Path)
616
+ parser.add_argument("--feature_path", type=Path)
617
+ args = parser.parse_args()
618
+ main(confs[args.conf], args.image_dir, args.export_dir, args.as_half)
hloc/extractors/__init__.py ADDED
File without changes
hloc/extractors/alike.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from hloc import 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
+ self.net = Alike_(
33
+ **configs[conf["model_name"]],
34
+ device=device,
35
+ top_k=conf["top_k"],
36
+ scores_th=conf["detection_threshold"],
37
+ n_limit=conf["max_keypoints"],
38
+ )
39
+ logger.info("Load Alike model done.")
40
+
41
+ def _forward(self, data):
42
+ image = data["image"]
43
+ image = image.permute(0, 2, 3, 1).squeeze()
44
+ image = image.cpu().numpy() * 255.0
45
+ pred = self.net(image, sub_pixel=self.conf["sub_pixel"])
46
+
47
+ keypoints = pred["keypoints"]
48
+ descriptors = pred["descriptors"]
49
+ scores = pred["scores"]
50
+
51
+ return {
52
+ "keypoints": torch.from_numpy(keypoints)[None],
53
+ "scores": torch.from_numpy(scores)[None],
54
+ "descriptors": torch.from_numpy(descriptors.T)[None],
55
+ }
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
+ }
hloc/extractors/d2net.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import torch
6
+
7
+ from hloc import logger
8
+
9
+ from ..utils.base_model import BaseModel
10
+
11
+ d2net_path = Path(__file__).parent / "../../third_party/d2net"
12
+ sys.path.append(str(d2net_path))
13
+ from lib.model_test import D2Net as _D2Net
14
+ from lib.pyramid import process_multiscale
15
+
16
+
17
+ class D2Net(BaseModel):
18
+ default_conf = {
19
+ "model_name": "d2_tf.pth",
20
+ "checkpoint_dir": d2net_path / "models",
21
+ "use_relu": True,
22
+ "multiscale": False,
23
+ "max_keypoints": 1024,
24
+ }
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ model_file = conf["checkpoint_dir"] / conf["model_name"]
29
+ if not model_file.exists():
30
+ model_file.parent.mkdir(exist_ok=True)
31
+ cmd = [
32
+ "wget",
33
+ "--quiet",
34
+ "https://dusmanu.com/files/d2-net/" + conf["model_name"],
35
+ "-O",
36
+ str(model_file),
37
+ ]
38
+ subprocess.run(cmd, check=True)
39
+
40
+ self.net = _D2Net(
41
+ model_file=model_file, use_relu=conf["use_relu"], use_cuda=False
42
+ )
43
+ logger.info("Load D2Net model done.")
44
+
45
+ def _forward(self, data):
46
+ image = data["image"]
47
+ image = image.flip(1) # RGB -> BGR
48
+ norm = image.new_tensor([103.939, 116.779, 123.68])
49
+ image = image * 255 - norm.view(1, 3, 1, 1) # caffe normalization
50
+
51
+ if self.conf["multiscale"]:
52
+ keypoints, scores, descriptors = process_multiscale(image, self.net)
53
+ else:
54
+ keypoints, scores, descriptors = process_multiscale(
55
+ image, self.net, scales=[1]
56
+ )
57
+ keypoints = keypoints[:, [1, 0]] # (x, y) and remove the scale
58
+
59
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
60
+ keypoints = keypoints[idxs, :2]
61
+ descriptors = descriptors[idxs]
62
+ scores = scores[idxs]
63
+
64
+ return {
65
+ "keypoints": torch.from_numpy(keypoints)[None],
66
+ "scores": torch.from_numpy(scores)[None],
67
+ "descriptors": torch.from_numpy(descriptors.T)[None],
68
+ }
hloc/extractors/darkfeat.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from hloc import logger
6
+
7
+ from ..utils.base_model import BaseModel
8
+
9
+ darkfeat_path = Path(__file__).parent / "../../third_party/DarkFeat"
10
+ sys.path.append(str(darkfeat_path))
11
+ from darkfeat import DarkFeat as DarkFeat_
12
+
13
+
14
+ class DarkFeat(BaseModel):
15
+ default_conf = {
16
+ "model_name": "DarkFeat.pth",
17
+ "max_keypoints": 1000,
18
+ "detection_threshold": 0.5,
19
+ "sub_pixel": False,
20
+ }
21
+ weight_urls = {
22
+ "DarkFeat.pth": "https://drive.google.com/uc?id=1Thl6m8NcmQ7zSAF-1_xaFs3F4H8UU6HX&confirm=t",
23
+ }
24
+ proxy = "http://localhost:1080"
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ model_path = darkfeat_path / "checkpoints" / conf["model_name"]
29
+ link = self.weight_urls[conf["model_name"]]
30
+ if not model_path.exists():
31
+ model_path.parent.mkdir(exist_ok=True)
32
+ cmd_wo_proxy = ["gdown", link, "-O", str(model_path)]
33
+ cmd = ["gdown", link, "-O", str(model_path), "--proxy", self.proxy]
34
+ logger.info(
35
+ f"Downloading the DarkFeat model with `{cmd_wo_proxy}`."
36
+ )
37
+ try:
38
+ subprocess.run(cmd_wo_proxy, check=True)
39
+ except subprocess.CalledProcessError as e:
40
+ logger.info(f"Downloading the model failed `{e}`.")
41
+ logger.info(f"Downloading the DarkFeat model with `{cmd}`.")
42
+ try:
43
+ subprocess.run(cmd, check=True)
44
+ except subprocess.CalledProcessError as e:
45
+ logger.error("Failed to download the DarkFeat model.")
46
+ raise e
47
+
48
+ self.net = DarkFeat_(model_path)
49
+ logger.info("Load DarkFeat model done.")
50
+
51
+ def _forward(self, data):
52
+ pred = self.net({"image": data["image"]})
53
+ keypoints = pred["keypoints"]
54
+ descriptors = pred["descriptors"]
55
+ scores = pred["scores"]
56
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
57
+ keypoints = keypoints[idxs, :2]
58
+ descriptors = descriptors[:, idxs]
59
+ scores = scores[idxs]
60
+ return {
61
+ "keypoints": keypoints[None], # 1 x N x 2
62
+ "scores": scores[None], # 1 x N
63
+ "descriptors": descriptors[None], # 1 x 128 x N
64
+ }
hloc/extractors/dedode.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ import torchvision.transforms as transforms
7
+
8
+ from hloc import logger
9
+
10
+ from ..utils.base_model import BaseModel
11
+
12
+ dedode_path = Path(__file__).parent / "../../third_party/DeDoDe"
13
+ sys.path.append(str(dedode_path))
14
+
15
+ from DeDoDe import dedode_descriptor_B, dedode_detector_L
16
+ from DeDoDe.utils import to_pixel_coords
17
+
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+
20
+
21
+ class DeDoDe(BaseModel):
22
+ default_conf = {
23
+ "name": "dedode",
24
+ "model_detector_name": "dedode_detector_L.pth",
25
+ "model_descriptor_name": "dedode_descriptor_B.pth",
26
+ "max_keypoints": 2000,
27
+ "match_threshold": 0.2,
28
+ "dense": False, # Now fixed to be false
29
+ }
30
+ required_inputs = [
31
+ "image",
32
+ ]
33
+ weight_urls = {
34
+ "dedode_detector_L.pth": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_detector_L.pth",
35
+ "dedode_descriptor_B.pth": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",
36
+ }
37
+
38
+ # Initialize the line matcher
39
+ def _init(self, conf):
40
+ model_detector_path = (
41
+ dedode_path / "pretrained" / conf["model_detector_name"]
42
+ )
43
+ model_descriptor_path = (
44
+ dedode_path / "pretrained" / conf["model_descriptor_name"]
45
+ )
46
+
47
+ self.normalizer = transforms.Normalize(
48
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
49
+ )
50
+ # Download the model.
51
+ if not model_detector_path.exists():
52
+ model_detector_path.parent.mkdir(exist_ok=True)
53
+ link = self.weight_urls[conf["model_detector_name"]]
54
+ cmd = ["wget", "--quiet", link, "-O", str(model_detector_path)]
55
+ logger.info(f"Downloading the DeDoDe detector model with `{cmd}`.")
56
+ subprocess.run(cmd, check=True)
57
+
58
+ if not model_descriptor_path.exists():
59
+ model_descriptor_path.parent.mkdir(exist_ok=True)
60
+ link = self.weight_urls[conf["model_descriptor_name"]]
61
+ cmd = ["wget", "--quiet", link, "-O", str(model_descriptor_path)]
62
+ logger.info(
63
+ f"Downloading the DeDoDe descriptor model with `{cmd}`."
64
+ )
65
+ subprocess.run(cmd, check=True)
66
+
67
+ # load the model
68
+ weights_detector = torch.load(model_detector_path, map_location="cpu")
69
+ weights_descriptor = torch.load(
70
+ model_descriptor_path, map_location="cpu"
71
+ )
72
+ self.detector = dedode_detector_L(
73
+ weights=weights_detector, device=device
74
+ )
75
+ self.descriptor = dedode_descriptor_B(
76
+ weights=weights_descriptor, device=device
77
+ )
78
+ logger.info("Load DeDoDe model done.")
79
+
80
+ def _forward(self, data):
81
+ """
82
+ data: dict, keys: {'image0','image1'}
83
+ image shape: N x C x H x W
84
+ color mode: RGB
85
+ """
86
+ img0 = self.normalizer(data["image"].squeeze()).float()[None]
87
+ H_A, W_A = img0.shape[2:]
88
+
89
+ # step 1: detect keypoints
90
+ detections_A = None
91
+ batch_A = {"image": img0}
92
+ if self.conf["dense"]:
93
+ detections_A = self.detector.detect_dense(batch_A)
94
+ else:
95
+ detections_A = self.detector.detect(
96
+ batch_A, num_keypoints=self.conf["max_keypoints"]
97
+ )
98
+ keypoints_A, P_A = detections_A["keypoints"], detections_A["confidence"]
99
+
100
+ # step 2: describe keypoints
101
+ # dim: 1 x N x 256
102
+ description_A = self.descriptor.describe_keypoints(
103
+ batch_A, keypoints_A
104
+ )["descriptions"]
105
+ keypoints_A = to_pixel_coords(keypoints_A, H_A, W_A)
106
+
107
+ return {
108
+ "keypoints": keypoints_A, # 1 x N x 2
109
+ "descriptors": description_A.permute(0, 2, 1), # 1 x 256 x N
110
+ "scores": P_A, # 1 x N
111
+ }
hloc/extractors/dir.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
13
+ str(Path(__file__).parent / "../../third_party/deep-image-retrieval")
14
+ )
15
+ os.environ["DB_ROOT"] = "" # required by dirtorch
16
+
17
+ from dirtorch.extract_features import load_model # noqa: E402
18
+ from dirtorch.utils import common # noqa: E402
19
+
20
+ # The DIR model checkpoints (pickle files) include sklearn.decomposition.pca,
21
+ # which has been deprecated in sklearn v0.24
22
+ # and must be explicitly imported with `from sklearn.decomposition import PCA`.
23
+ # This is a hacky workaround to maintain forward compatibility.
24
+ sys.modules["sklearn.decomposition.pca"] = sklearn.decomposition._pca
25
+
26
+
27
+ class DIR(BaseModel):
28
+ default_conf = {
29
+ "model_name": "Resnet-101-AP-GeM",
30
+ "whiten_name": "Landmarks_clean",
31
+ "whiten_params": {
32
+ "whitenp": 0.25,
33
+ "whitenv": None,
34
+ "whitenm": 1.0,
35
+ },
36
+ "pooling": "gem",
37
+ "gemp": 3,
38
+ }
39
+ required_inputs = ["image"]
40
+
41
+ dir_models = {
42
+ "Resnet-101-AP-GeM": "https://docs.google.com/uc?export=download&id=1UWJGDuHtzaQdFhSMojoYVQjmCXhIwVvy",
43
+ }
44
+
45
+ def _init(self, conf):
46
+ checkpoint = Path(
47
+ torch.hub.get_dir(), "dirtorch", conf["model_name"] + ".pt"
48
+ )
49
+ if not checkpoint.exists():
50
+ checkpoint.parent.mkdir(exist_ok=True, parents=True)
51
+ link = self.dir_models[conf["model_name"]]
52
+ gdown.download(str(link), str(checkpoint) + ".zip", quiet=False)
53
+ zf = ZipFile(str(checkpoint) + ".zip", "r")
54
+ zf.extractall(checkpoint.parent)
55
+ zf.close()
56
+ os.remove(str(checkpoint) + ".zip")
57
+
58
+ self.net = load_model(checkpoint, False) # first load on CPU
59
+ if conf["whiten_name"]:
60
+ assert conf["whiten_name"] in self.net.pca
61
+
62
+ def _forward(self, data):
63
+ image = data["image"]
64
+ assert image.shape[1] == 3
65
+ mean = self.net.preprocess["mean"]
66
+ std = self.net.preprocess["std"]
67
+ image = image - image.new_tensor(mean)[:, None, None]
68
+ image = image / image.new_tensor(std)[:, None, None]
69
+
70
+ desc = self.net(image)
71
+ desc = desc.unsqueeze(0) # batch dimension
72
+ if self.conf["whiten_name"]:
73
+ pca = self.net.pca[self.conf["whiten_name"]]
74
+ desc = common.whiten_features(
75
+ desc.cpu().numpy(), pca, **self.conf["whiten_params"]
76
+ )
77
+ desc = torch.from_numpy(desc)
78
+
79
+ return {
80
+ "global_descriptor": desc,
81
+ }
hloc/extractors/disk.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia
2
+
3
+ from hloc 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
+ }
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
+ }
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
+ }
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
+ }
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}
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
+ }
hloc/extractors/lanet.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from hloc import 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": "v0",
22
+ "keypoint_threshold": 0.1,
23
+ "max_keypoints": 1024,
24
+ }
25
+ required_inputs = ["image"]
26
+
27
+ def _init(self, conf):
28
+ model_path = (
29
+ lanet_path / "checkpoints" / f'PointModel_{conf["model_name"]}.pth'
30
+ )
31
+ if not model_path.exists():
32
+ logger.warning(f"No model found at {model_path}, start downloading")
33
+ self.net = PointModel(is_test=True)
34
+ state_dict = torch.load(model_path, map_location="cpu")
35
+ self.net.load_state_dict(state_dict["model_state"])
36
+ logger.info("Load LANet model done.")
37
+
38
+ def _forward(self, data):
39
+ image = data["image"]
40
+ keypoints, scores, descriptors = self.net(image)
41
+ _, _, Hc, Wc = descriptors.shape
42
+
43
+ # Scores & Descriptors
44
+ kpts_score = torch.cat([keypoints, scores], dim=1).view(3, -1).t()
45
+ descriptors = descriptors.view(256, Hc, Wc).view(256, -1).t()
46
+
47
+ # Filter based on confidence threshold
48
+ descriptors = descriptors[
49
+ kpts_score[:, 0] > self.conf["keypoint_threshold"], :
50
+ ]
51
+ kpts_score = kpts_score[
52
+ kpts_score[:, 0] > self.conf["keypoint_threshold"], :
53
+ ]
54
+ keypoints = kpts_score[:, 1:]
55
+ scores = kpts_score[:, 0]
56
+
57
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
58
+ keypoints = keypoints[idxs, :2]
59
+ descriptors = descriptors[idxs]
60
+ scores = scores[idxs]
61
+
62
+ return {
63
+ "keypoints": keypoints[None],
64
+ "scores": scores[None],
65
+ "descriptors": descriptors.T[None],
66
+ }
hloc/extractors/netvlad.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
21
+ input_dim, K, kernel_size=1, bias=score_bias
22
+ )
23
+ centers = nn.parameter.Parameter(torch.empty([input_dim, K]))
24
+ nn.init.xavier_uniform_(centers)
25
+ self.register_parameter("centers", centers)
26
+ self.intranorm = intranorm
27
+ self.output_dim = input_dim * K
28
+
29
+ def forward(self, x):
30
+ b = x.size(0)
31
+ scores = self.score_proj(x)
32
+ scores = F.softmax(scores, dim=1)
33
+ diff = x.unsqueeze(2) - self.centers.unsqueeze(0).unsqueeze(-1)
34
+ desc = (scores.unsqueeze(1) * diff).sum(dim=-1)
35
+ if self.intranorm:
36
+ # From the official MATLAB implementation.
37
+ desc = F.normalize(desc, dim=1)
38
+ desc = desc.view(b, -1)
39
+ desc = F.normalize(desc, dim=1)
40
+ return desc
41
+
42
+
43
+ class NetVLAD(BaseModel):
44
+ default_conf = {"model_name": "VGG16-NetVLAD-Pitts30K", "whiten": True}
45
+ required_inputs = ["image"]
46
+
47
+ # Models exported using
48
+ # https://github.com/uzh-rpg/netvlad_tf_open/blob/master/matlab/net_class2struct.m.
49
+ dir_models = {
50
+ "VGG16-NetVLAD-Pitts30K": "https://cvg-data.inf.ethz.ch/hloc/netvlad/Pitts30K_struct.mat",
51
+ "VGG16-NetVLAD-TokyoTM": "https://cvg-data.inf.ethz.ch/hloc/netvlad/TokyoTM_struct.mat",
52
+ }
53
+
54
+ def _init(self, conf):
55
+ assert conf["model_name"] in self.dir_models.keys()
56
+
57
+ # Download the checkpoint.
58
+ checkpoint = Path(
59
+ torch.hub.get_dir(), "netvlad", conf["model_name"] + ".mat"
60
+ )
61
+ if not checkpoint.exists():
62
+ checkpoint.parent.mkdir(exist_ok=True, parents=True)
63
+ link = self.dir_models[conf["model_name"]]
64
+ cmd = ["wget", "--quiet", link, "-O", str(checkpoint)]
65
+ logger.info(f"Downloading the NetVLAD model with `{cmd}`.")
66
+ subprocess.run(cmd, check=True)
67
+
68
+ # Create the network.
69
+ # Remove classification head.
70
+ backbone = list(models.vgg16().children())[0]
71
+ # Remove last ReLU + MaxPool2d.
72
+ self.backbone = nn.Sequential(*list(backbone.children())[:-2])
73
+
74
+ self.netvlad = NetVLADLayer()
75
+
76
+ if conf["whiten"]:
77
+ self.whiten = nn.Linear(self.netvlad.output_dim, 4096)
78
+
79
+ # Parse MATLAB weights using https://github.com/uzh-rpg/netvlad_tf_open
80
+ mat = loadmat(checkpoint, struct_as_record=False, squeeze_me=True)
81
+
82
+ # CNN weights.
83
+ for layer, mat_layer in zip(
84
+ self.backbone.children(), mat["net"].layers
85
+ ):
86
+ if isinstance(layer, nn.Conv2d):
87
+ w = mat_layer.weights[0] # Shape: S x S x IN x OUT
88
+ b = mat_layer.weights[1] # Shape: OUT
89
+ # Prepare for PyTorch - enforce float32 and right shape.
90
+ # w should have shape: OUT x IN x S x S
91
+ # b should have shape: OUT
92
+ w = torch.tensor(w).float().permute([3, 2, 0, 1])
93
+ b = torch.tensor(b).float()
94
+ # Update layer weights.
95
+ layer.weight = nn.Parameter(w)
96
+ layer.bias = nn.Parameter(b)
97
+
98
+ # NetVLAD weights.
99
+ score_w = mat["net"].layers[30].weights[0] # D x K
100
+ # centers are stored as opposite in official MATLAB code
101
+ center_w = -mat["net"].layers[30].weights[1] # D x K
102
+ # Prepare for PyTorch - make sure it is float32 and has right shape.
103
+ # score_w should have shape K x D x 1
104
+ # center_w should have shape D x K
105
+ score_w = torch.tensor(score_w).float().permute([1, 0]).unsqueeze(-1)
106
+ center_w = torch.tensor(center_w).float()
107
+ # Update layer weights.
108
+ self.netvlad.score_proj.weight = nn.Parameter(score_w)
109
+ self.netvlad.centers = nn.Parameter(center_w)
110
+
111
+ # Whitening weights.
112
+ if conf["whiten"]:
113
+ w = mat["net"].layers[33].weights[0] # Shape: 1 x 1 x IN x OUT
114
+ b = mat["net"].layers[33].weights[1] # Shape: OUT
115
+ # Prepare for PyTorch - make sure it is float32 and has right shape
116
+ w = torch.tensor(w).float().squeeze().permute([1, 0]) # OUT x IN
117
+ b = torch.tensor(b.squeeze()).float() # Shape: OUT
118
+ # Update layer weights.
119
+ self.whiten.weight = nn.Parameter(w)
120
+ self.whiten.bias = nn.Parameter(b)
121
+
122
+ # Preprocessing parameters.
123
+ self.preprocess = {
124
+ "mean": mat["net"].meta.normalization.averageImage[0, 0],
125
+ "std": np.array([1, 1, 1], dtype=np.float32),
126
+ }
127
+
128
+ def _forward(self, data):
129
+ image = data["image"]
130
+ assert image.shape[1] == 3
131
+ assert image.min() >= -EPS and image.max() <= 1 + EPS
132
+ image = torch.clamp(image * 255, 0.0, 255.0) # Input should be 0-255.
133
+ mean = self.preprocess["mean"]
134
+ std = self.preprocess["std"]
135
+ image = image - image.new_tensor(mean).view(1, -1, 1, 1)
136
+ image = image / image.new_tensor(std).view(1, -1, 1, 1)
137
+
138
+ # Feature extraction.
139
+ descriptors = self.backbone(image)
140
+ b, c, _, _ = descriptors.size()
141
+ descriptors = descriptors.view(b, c, -1)
142
+
143
+ # NetVLAD layer.
144
+ descriptors = F.normalize(descriptors, dim=1) # Pre-normalization.
145
+ desc = self.netvlad(descriptors)
146
+
147
+ # Whiten if needed.
148
+ if hasattr(self, "whiten"):
149
+ desc = self.whiten(desc)
150
+ desc = F.normalize(desc, dim=1) # Final L2 normalization.
151
+
152
+ return {"global_descriptor": desc}
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
+ }
hloc/extractors/r2d2.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torchvision.transforms as tvf
5
+
6
+ from hloc import logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ r2d2_path = Path(__file__).parent / "../../third_party/r2d2"
11
+ sys.path.append(str(r2d2_path))
12
+ from extract import NonMaxSuppression, extract_multiscale, load_network
13
+
14
+
15
+ class R2D2(BaseModel):
16
+ default_conf = {
17
+ "model_name": "r2d2_WASF_N16.pt",
18
+ "max_keypoints": 5000,
19
+ "scale_factor": 2**0.25,
20
+ "min_size": 256,
21
+ "max_size": 1024,
22
+ "min_scale": 0,
23
+ "max_scale": 1,
24
+ "reliability_threshold": 0.7,
25
+ "repetability_threshold": 0.7,
26
+ }
27
+ required_inputs = ["image"]
28
+
29
+ def _init(self, conf):
30
+ model_fn = r2d2_path / "models" / conf["model_name"]
31
+ self.norm_rgb = tvf.Normalize(
32
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
33
+ )
34
+ self.net = load_network(model_fn)
35
+ self.detector = NonMaxSuppression(
36
+ rel_thr=conf["reliability_threshold"],
37
+ rep_thr=conf["repetability_threshold"],
38
+ )
39
+ logger.info("Load R2D2 model done.")
40
+
41
+ def _forward(self, data):
42
+ img = data["image"]
43
+ img = self.norm_rgb(img)
44
+
45
+ xys, desc, scores = extract_multiscale(
46
+ self.net,
47
+ img,
48
+ self.detector,
49
+ scale_f=self.conf["scale_factor"],
50
+ min_size=self.conf["min_size"],
51
+ max_size=self.conf["max_size"],
52
+ min_scale=self.conf["min_scale"],
53
+ max_scale=self.conf["max_scale"],
54
+ )
55
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
56
+ xy = xys[idxs, :2]
57
+ desc = desc[idxs].t()
58
+ scores = scores[idxs]
59
+
60
+ pred = {
61
+ "keypoints": xy[None],
62
+ "descriptors": desc[None],
63
+ "scores": scores[None],
64
+ }
65
+ return pred
hloc/extractors/rekd.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from hloc import 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
+ model_path = (
26
+ rekd_path / "checkpoints" / f'PointModel_{conf["model_name"]}.pth'
27
+ )
28
+ if not model_path.exists():
29
+ print(f"No model found at {model_path}")
30
+ self.net = REKD_(is_test=True)
31
+ state_dict = torch.load(model_path, map_location="cpu")
32
+ self.net.load_state_dict(state_dict["model_state"])
33
+ logger.info("Load REKD model done.")
34
+
35
+ def _forward(self, data):
36
+ image = data["image"]
37
+ keypoints, scores, descriptors = self.net(image)
38
+ _, _, Hc, Wc = descriptors.shape
39
+
40
+ # Scores & Descriptors
41
+ kpts_score = (
42
+ torch.cat([keypoints, scores], dim=1)
43
+ .view(3, -1)
44
+ .t()
45
+ .cpu()
46
+ .detach()
47
+ .numpy()
48
+ )
49
+ descriptors = (
50
+ descriptors.view(256, Hc, Wc)
51
+ .view(256, -1)
52
+ .t()
53
+ .cpu()
54
+ .detach()
55
+ .numpy()
56
+ )
57
+
58
+ # Filter based on confidence threshold
59
+ descriptors = descriptors[
60
+ kpts_score[:, 0] > self.conf["keypoint_threshold"], :
61
+ ]
62
+ kpts_score = kpts_score[
63
+ kpts_score[:, 0] > self.conf["keypoint_threshold"], :
64
+ ]
65
+ keypoints = kpts_score[:, 1:]
66
+ scores = kpts_score[:, 0]
67
+
68
+ return {
69
+ "keypoints": torch.from_numpy(keypoints)[None],
70
+ "scores": torch.from_numpy(scores)[None],
71
+ "descriptors": torch.from_numpy(descriptors.T)[None],
72
+ }
hloc/extractors/rord.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import torch
6
+
7
+ from hloc import logger
8
+
9
+ from ..utils.base_model import BaseModel
10
+
11
+ rord_path = Path(__file__).parent / "../../third_party"
12
+ sys.path.append(str(rord_path))
13
+ from RoRD.lib.model_test import D2Net as _RoRD
14
+ from RoRD.lib.pyramid import process_multiscale
15
+
16
+
17
+ class RoRD(BaseModel):
18
+ default_conf = {
19
+ "model_name": "rord.pth",
20
+ "checkpoint_dir": rord_path / "RoRD" / "models",
21
+ "use_relu": True,
22
+ "multiscale": False,
23
+ "max_keypoints": 1024,
24
+ }
25
+ required_inputs = ["image"]
26
+ weight_urls = {
27
+ "rord.pth": "https://drive.google.com/uc?id=12414ZGKwgPAjNTGtNrlB4VV9l7W76B2o&confirm=t",
28
+ }
29
+ proxy = "http://localhost:1080"
30
+
31
+ def _init(self, conf):
32
+ model_path = conf["checkpoint_dir"] / conf["model_name"]
33
+ link = self.weight_urls[conf["model_name"]]
34
+ if not model_path.exists():
35
+ model_path.parent.mkdir(exist_ok=True)
36
+ cmd_wo_proxy = ["gdown", link, "-O", str(model_path)]
37
+ cmd = ["gdown", link, "-O", str(model_path), "--proxy", self.proxy]
38
+ logger.info(f"Downloading the RoRD model with `{cmd_wo_proxy}`.")
39
+ try:
40
+ subprocess.run(cmd_wo_proxy, check=True)
41
+ except subprocess.CalledProcessError as e:
42
+ logger.info(f"Downloading failed {e}.")
43
+ logger.info(f"Downloading the RoRD model with {cmd}.")
44
+ try:
45
+ subprocess.run(cmd, check=True)
46
+ except subprocess.CalledProcessError as e:
47
+ logger.error(f"Failed to download the RoRD model: {e}")
48
+ self.net = _RoRD(
49
+ model_file=model_path, use_relu=conf["use_relu"], use_cuda=False
50
+ )
51
+ logger.info("Load RoRD model done.")
52
+
53
+ def _forward(self, data):
54
+ image = data["image"]
55
+ image = image.flip(1) # RGB -> BGR
56
+ norm = image.new_tensor([103.939, 116.779, 123.68])
57
+ image = image * 255 - norm.view(1, 3, 1, 1) # caffe normalization
58
+
59
+ if self.conf["multiscale"]:
60
+ keypoints, scores, descriptors = process_multiscale(image, self.net)
61
+ else:
62
+ keypoints, scores, descriptors = process_multiscale(
63
+ image, self.net, scales=[1]
64
+ )
65
+ keypoints = keypoints[:, [1, 0]] # (x, y) and remove the scale
66
+
67
+ idxs = scores.argsort()[-self.conf["max_keypoints"] or None :]
68
+ keypoints = keypoints[idxs, :2]
69
+ descriptors = descriptors[idxs]
70
+ scores = scores[idxs]
71
+
72
+ return {
73
+ "keypoints": torch.from_numpy(keypoints)[None],
74
+ "scores": torch.from_numpy(scores)[None],
75
+ "descriptors": torch.from_numpy(descriptors.T)[None],
76
+ }
hloc/extractors/sfd2.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torchvision.transforms as tvf
5
+
6
+ from .. import logger
7
+ from ..utils.base_model import BaseModel
8
+
9
+ tp_path = Path(__file__).parent / "../../third_party"
10
+ sys.path.append(str(tp_path))
11
+ from pram.nets.sfd2 import load_sfd2
12
+
13
+
14
+ class SFD2(BaseModel):
15
+ default_conf = {
16
+ "max_keypoints": 4096,
17
+ "model_name": "sfd2_20230511_210205_resnet4x.79.pth",
18
+ "conf_th": 0.001,
19
+ }
20
+ required_inputs = ["image"]
21
+
22
+ def _init(self, conf):
23
+ self.conf = {**self.default_conf, **conf}
24
+ self.norm_rgb = tvf.Normalize(
25
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
26
+ )
27
+ model_path = tp_path / "pram" / "weights" / self.conf["model_name"]
28
+ self.net = load_sfd2(weight_path=model_path).eval()
29
+
30
+ logger.info("Load SFD2 model done.")
31
+
32
+ def _forward(self, data):
33
+ pred = self.net.extract_local_global(
34
+ data={"image": self.norm_rgb(data["image"])}, config=self.conf
35
+ )
36
+ out = {
37
+ "keypoints": pred["keypoints"][0][None],
38
+ "scores": pred["scores"][0][None],
39
+ "descriptors": pred["descriptors"][0][None],
40
+ }
41
+ return out
hloc/extractors/sift.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ from kornia.color import rgb_to_grayscale
7
+ from omegaconf import OmegaConf
8
+ from packaging import version
9
+
10
+ try:
11
+ import pycolmap
12
+ except ImportError:
13
+ pycolmap = None
14
+ from hloc import logger
15
+
16
+ from ..utils.base_model import BaseModel
17
+
18
+
19
+ def filter_dog_point(
20
+ points, scales, angles, image_shape, nms_radius, scores=None
21
+ ):
22
+ h, w = image_shape
23
+ ij = np.round(points - 0.5).astype(int).T[::-1]
24
+
25
+ # Remove duplicate points (identical coordinates).
26
+ # Pick highest scale or score
27
+ s = scales if scores is None else scores
28
+ buffer = np.zeros((h, w))
29
+ np.maximum.at(buffer, tuple(ij), s)
30
+ keep = np.where(buffer[tuple(ij)] == s)[0]
31
+
32
+ # Pick lowest angle (arbitrary).
33
+ ij = ij[:, keep]
34
+ buffer[:] = np.inf
35
+ o_abs = np.abs(angles[keep])
36
+ np.minimum.at(buffer, tuple(ij), o_abs)
37
+ mask = buffer[tuple(ij)] == o_abs
38
+ ij = ij[:, mask]
39
+ keep = keep[mask]
40
+
41
+ if nms_radius > 0:
42
+ # Apply NMS on the remaining points
43
+ buffer[:] = 0
44
+ buffer[tuple(ij)] = s[keep] # scores or scale
45
+
46
+ local_max = torch.nn.functional.max_pool2d(
47
+ torch.from_numpy(buffer).unsqueeze(0),
48
+ kernel_size=nms_radius * 2 + 1,
49
+ stride=1,
50
+ padding=nms_radius,
51
+ ).squeeze(0)
52
+ is_local_max = buffer == local_max.numpy()
53
+ keep = keep[is_local_max[tuple(ij)]]
54
+ return keep
55
+
56
+
57
+ def sift_to_rootsift(x: torch.Tensor, eps=1e-6) -> torch.Tensor:
58
+ x = torch.nn.functional.normalize(x, p=1, dim=-1, eps=eps)
59
+ x.clip_(min=eps).sqrt_()
60
+ return torch.nn.functional.normalize(x, p=2, dim=-1, eps=eps)
61
+
62
+
63
+ def run_opencv_sift(features: cv2.Feature2D, image: np.ndarray) -> np.ndarray:
64
+ """
65
+ Detect keypoints using OpenCV Detector.
66
+ Optionally, perform description.
67
+ Args:
68
+ features: OpenCV based keypoints detector and descriptor
69
+ image: Grayscale image of uint8 data type
70
+ Returns:
71
+ keypoints: 1D array of detected cv2.KeyPoint
72
+ scores: 1D array of responses
73
+ descriptors: 1D array of descriptors
74
+ """
75
+ detections, descriptors = features.detectAndCompute(image, None)
76
+ points = np.array([k.pt for k in detections], dtype=np.float32)
77
+ scores = np.array([k.response for k in detections], dtype=np.float32)
78
+ scales = np.array([k.size for k in detections], dtype=np.float32)
79
+ angles = np.deg2rad(
80
+ np.array([k.angle for k in detections], dtype=np.float32)
81
+ )
82
+ return points, scores, scales, angles, descriptors
83
+
84
+
85
+ class SIFT(BaseModel):
86
+ default_conf = {
87
+ "rootsift": True,
88
+ "nms_radius": 0, # None to disable filtering entirely.
89
+ "max_keypoints": 4096,
90
+ "backend": "opencv", # in {opencv, pycolmap, pycolmap_cpu, pycolmap_cuda}
91
+ "detection_threshold": 0.0066667, # from COLMAP
92
+ "edge_threshold": 10,
93
+ "first_octave": -1, # only used by pycolmap, the default of COLMAP
94
+ "num_octaves": 4,
95
+ }
96
+
97
+ required_data_keys = ["image"]
98
+
99
+ def _init(self, conf):
100
+ self.conf = OmegaConf.create(self.conf)
101
+ backend = self.conf.backend
102
+ if backend.startswith("pycolmap"):
103
+ if pycolmap is None:
104
+ raise ImportError(
105
+ "Cannot find module pycolmap: install it with pip"
106
+ "or use backend=opencv."
107
+ )
108
+ options = {
109
+ "peak_threshold": self.conf.detection_threshold,
110
+ "edge_threshold": self.conf.edge_threshold,
111
+ "first_octave": self.conf.first_octave,
112
+ "num_octaves": self.conf.num_octaves,
113
+ "normalization": pycolmap.Normalization.L2, # L1_ROOT is buggy.
114
+ }
115
+ device = (
116
+ "auto"
117
+ if backend == "pycolmap"
118
+ else backend.replace("pycolmap_", "")
119
+ )
120
+ if (
121
+ backend == "pycolmap_cpu" or not pycolmap.has_cuda
122
+ ) and pycolmap.__version__ < "0.5.0":
123
+ warnings.warn(
124
+ "The pycolmap CPU SIFT is buggy in version < 0.5.0, "
125
+ "consider upgrading pycolmap or use the CUDA version.",
126
+ stacklevel=1,
127
+ )
128
+ else:
129
+ options["max_num_features"] = self.conf.max_keypoints
130
+ self.sift = pycolmap.Sift(options=options, device=device)
131
+ elif backend == "opencv":
132
+ self.sift = cv2.SIFT_create(
133
+ contrastThreshold=self.conf.detection_threshold,
134
+ nfeatures=self.conf.max_keypoints,
135
+ edgeThreshold=self.conf.edge_threshold,
136
+ nOctaveLayers=self.conf.num_octaves,
137
+ )
138
+ else:
139
+ backends = {"opencv", "pycolmap", "pycolmap_cpu", "pycolmap_cuda"}
140
+ raise ValueError(
141
+ f"Unknown backend: {backend} not in "
142
+ f"{{{','.join(backends)}}}."
143
+ )
144
+ logger.info("Load SIFT model done.")
145
+
146
+ def extract_single_image(self, image: torch.Tensor):
147
+ image_np = image.cpu().numpy().squeeze(0)
148
+
149
+ if self.conf.backend.startswith("pycolmap"):
150
+ if version.parse(pycolmap.__version__) >= version.parse("0.5.0"):
151
+ detections, descriptors = self.sift.extract(image_np)
152
+ scores = None # Scores are not exposed by COLMAP anymore.
153
+ else:
154
+ detections, scores, descriptors = self.sift.extract(image_np)
155
+ keypoints = detections[:, :2] # Keep only (x, y).
156
+ scales, angles = detections[:, -2:].T
157
+ if scores is not None and (
158
+ self.conf.backend == "pycolmap_cpu" or not pycolmap.has_cuda
159
+ ):
160
+ # Set the scores as a combination of abs. response and scale.
161
+ scores = np.abs(scores) * scales
162
+ elif self.conf.backend == "opencv":
163
+ # TODO: Check if opencv keypoints are already in corner convention
164
+ keypoints, scores, scales, angles, descriptors = run_opencv_sift(
165
+ self.sift, (image_np * 255.0).astype(np.uint8)
166
+ )
167
+ pred = {
168
+ "keypoints": keypoints,
169
+ "scales": scales,
170
+ "oris": angles,
171
+ "descriptors": descriptors,
172
+ }
173
+ if scores is not None:
174
+ pred["scores"] = scores
175
+
176
+ # sometimes pycolmap returns points outside the image. We remove them
177
+ if self.conf.backend.startswith("pycolmap"):
178
+ is_inside = (
179
+ pred["keypoints"] + 0.5 < np.array([image_np.shape[-2:][::-1]])
180
+ ).all(-1)
181
+ pred = {k: v[is_inside] for k, v in pred.items()}
182
+
183
+ if self.conf.nms_radius is not None:
184
+ keep = filter_dog_point(
185
+ pred["keypoints"],
186
+ pred["scales"],
187
+ pred["oris"],
188
+ image_np.shape,
189
+ self.conf.nms_radius,
190
+ scores=pred.get("scores"),
191
+ )
192
+ pred = {k: v[keep] for k, v in pred.items()}
193
+
194
+ pred = {k: torch.from_numpy(v) for k, v in pred.items()}
195
+ if scores is not None:
196
+ # Keep the k keypoints with highest score
197
+ num_points = self.conf.max_keypoints
198
+ if num_points is not None and len(pred["keypoints"]) > num_points:
199
+ indices = torch.topk(pred["scores"], num_points).indices
200
+ pred = {k: v[indices] for k, v in pred.items()}
201
+ return pred
202
+
203
+ def _forward(self, data: dict) -> dict:
204
+ image = data["image"]
205
+ if image.shape[1] == 3:
206
+ image = rgb_to_grayscale(image)
207
+ device = image.device
208
+ image = image.cpu()
209
+ pred = []
210
+ for k in range(len(image)):
211
+ img = image[k]
212
+ if "image_size" in data.keys():
213
+ # avoid extracting points in padded areas
214
+ w, h = data["image_size"][k]
215
+ img = img[:, :h, :w]
216
+ p = self.extract_single_image(img)
217
+ pred.append(p)
218
+ pred = {
219
+ k: torch.stack([p[k] for p in pred], 0).to(device) for k in pred[0]
220
+ }
221
+ if self.conf.rootsift:
222
+ pred["descriptors"] = sift_to_rootsift(pred["descriptors"])
223
+ pred["descriptors"] = pred["descriptors"].permute(0, 2, 1)
224
+ pred["keypoint_scores"] = pred["scores"].clone()
225
+ return pred
hloc/extractors/superpoint.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import torch
5
+
6
+ from hloc import logger
7
+
8
+ from ..utils.base_model import BaseModel
9
+
10
+ sys.path.append(str(Path(__file__).parent / "../../third_party"))
11
+ from SuperGluePretrainedNetwork.models import superpoint # noqa E402
12
+
13
+
14
+ # The original keypoint sampling is incorrect. We patch it here but
15
+ # we don't fix it upstream to not impact exisiting evaluations.
16
+ def sample_descriptors_fix_sampling(keypoints, descriptors, s: int = 8):
17
+ """Interpolate descriptors at keypoint locations"""
18
+ b, c, h, w = descriptors.shape
19
+ keypoints = (keypoints + 0.5) / (keypoints.new_tensor([w, h]) * s)
20
+ keypoints = keypoints * 2 - 1 # normalize to (-1, 1)
21
+ descriptors = torch.nn.functional.grid_sample(
22
+ descriptors,
23
+ keypoints.view(b, 1, -1, 2),
24
+ mode="bilinear",
25
+ align_corners=False,
26
+ )
27
+ descriptors = torch.nn.functional.normalize(
28
+ descriptors.reshape(b, c, -1), p=2, dim=1
29
+ )
30
+ return descriptors
31
+
32
+
33
+ class SuperPoint(BaseModel):
34
+ default_conf = {
35
+ "nms_radius": 4,
36
+ "keypoint_threshold": 0.005,
37
+ "max_keypoints": -1,
38
+ "remove_borders": 4,
39
+ "fix_sampling": False,
40
+ }
41
+ required_inputs = ["image"]
42
+ detection_noise = 2.0
43
+
44
+ def _init(self, conf):
45
+ if conf["fix_sampling"]:
46
+ superpoint.sample_descriptors = sample_descriptors_fix_sampling
47
+ self.net = superpoint.SuperPoint(conf)
48
+ logger.info("Load SuperPoint model done.")
49
+
50
+ def _forward(self, data):
51
+ return self.net(data, self.conf)
hloc/extractors/xfeat.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from hloc import logger
4
+
5
+ from ..utils.base_model import BaseModel
6
+
7
+
8
+ class XFeat(BaseModel):
9
+ default_conf = {
10
+ "keypoint_threshold": 0.005,
11
+ "max_keypoints": -1,
12
+ }
13
+ required_inputs = ["image"]
14
+
15
+ def _init(self, conf):
16
+ self.net = torch.hub.load(
17
+ "verlab/accelerated_features",
18
+ "XFeat",
19
+ pretrained=True,
20
+ top_k=self.conf["max_keypoints"],
21
+ )
22
+ logger.info("Load XFeat(sparse) model done.")
23
+
24
+ def _forward(self, data):
25
+ pred = self.net.detectAndCompute(
26
+ data["image"], top_k=self.conf["max_keypoints"]
27
+ )[0]
28
+ pred = {
29
+ "keypoints": pred["keypoints"][None],
30
+ "scores": pred["scores"][None],
31
+ "descriptors": pred["descriptors"].T[None],
32
+ }
33
+ return pred
hloc/localize_inloc.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pickle
3
+ from pathlib import Path
4
+
5
+ import cv2
6
+ import h5py
7
+ import numpy as np
8
+ import pycolmap
9
+ import torch
10
+ from scipy.io import loadmat
11
+ from tqdm import tqdm
12
+
13
+ from . import logger
14
+ from .utils.parsers import names_to_pair, parse_retrieval
15
+
16
+
17
+ def interpolate_scan(scan, kp):
18
+ h, w, c = scan.shape
19
+ kp = kp / np.array([[w - 1, h - 1]]) * 2 - 1
20
+ assert np.all(kp > -1) and np.all(kp < 1)
21
+ scan = torch.from_numpy(scan).permute(2, 0, 1)[None]
22
+ kp = torch.from_numpy(kp)[None, None]
23
+ grid_sample = torch.nn.functional.grid_sample
24
+
25
+ # To maximize the number of points that have depth:
26
+ # do bilinear interpolation first and then nearest for the remaining points
27
+ interp_lin = grid_sample(scan, kp, align_corners=True, mode="bilinear")[
28
+ 0, :, 0
29
+ ]
30
+ interp_nn = torch.nn.functional.grid_sample(
31
+ scan, kp, align_corners=True, mode="nearest"
32
+ )[0, :, 0]
33
+ interp = torch.where(torch.isnan(interp_lin), interp_nn, interp_lin)
34
+ valid = ~torch.any(torch.isnan(interp), 0)
35
+
36
+ kp3d = interp.T.numpy()
37
+ valid = valid.numpy()
38
+ return kp3d, valid
39
+
40
+
41
+ def get_scan_pose(dataset_dir, rpath):
42
+ split_image_rpath = rpath.split("/")
43
+ floor_name = split_image_rpath[-3]
44
+ scan_id = split_image_rpath[-2]
45
+ image_name = split_image_rpath[-1]
46
+ building_name = image_name[:3]
47
+
48
+ path = Path(
49
+ dataset_dir,
50
+ "database/alignments",
51
+ floor_name,
52
+ f"transformations/{building_name}_trans_{scan_id}.txt",
53
+ )
54
+ with open(path) as f:
55
+ raw_lines = f.readlines()
56
+
57
+ P_after_GICP = np.array(
58
+ [
59
+ np.fromstring(raw_lines[7], sep=" "),
60
+ np.fromstring(raw_lines[8], sep=" "),
61
+ np.fromstring(raw_lines[9], sep=" "),
62
+ np.fromstring(raw_lines[10], sep=" "),
63
+ ]
64
+ )
65
+
66
+ return P_after_GICP
67
+
68
+
69
+ def pose_from_cluster(
70
+ dataset_dir, q, retrieved, feature_file, match_file, skip=None
71
+ ):
72
+ height, width = cv2.imread(str(dataset_dir / q)).shape[:2]
73
+ cx = 0.5 * width
74
+ cy = 0.5 * height
75
+ focal_length = 4032.0 * 28.0 / 36.0
76
+
77
+ all_mkpq = []
78
+ all_mkpr = []
79
+ all_mkp3d = []
80
+ all_indices = []
81
+ kpq = feature_file[q]["keypoints"].__array__()
82
+ num_matches = 0
83
+
84
+ for i, r in enumerate(retrieved):
85
+ kpr = feature_file[r]["keypoints"].__array__()
86
+ pair = names_to_pair(q, r)
87
+ m = match_file[pair]["matches0"].__array__()
88
+ v = m > -1
89
+
90
+ if skip and (np.count_nonzero(v) < skip):
91
+ continue
92
+
93
+ mkpq, mkpr = kpq[v], kpr[m[v]]
94
+ num_matches += len(mkpq)
95
+
96
+ scan_r = loadmat(Path(dataset_dir, r + ".mat"))["XYZcut"]
97
+ mkp3d, valid = interpolate_scan(scan_r, mkpr)
98
+ Tr = get_scan_pose(dataset_dir, r)
99
+ mkp3d = (Tr[:3, :3] @ mkp3d.T + Tr[:3, -1:]).T
100
+
101
+ all_mkpq.append(mkpq[valid])
102
+ all_mkpr.append(mkpr[valid])
103
+ all_mkp3d.append(mkp3d[valid])
104
+ all_indices.append(np.full(np.count_nonzero(valid), i))
105
+
106
+ all_mkpq = np.concatenate(all_mkpq, 0)
107
+ all_mkpr = np.concatenate(all_mkpr, 0)
108
+ all_mkp3d = np.concatenate(all_mkp3d, 0)
109
+ all_indices = np.concatenate(all_indices, 0)
110
+
111
+ cfg = {
112
+ "model": "SIMPLE_PINHOLE",
113
+ "width": width,
114
+ "height": height,
115
+ "params": [focal_length, cx, cy],
116
+ }
117
+ ret = pycolmap.absolute_pose_estimation(all_mkpq, all_mkp3d, cfg, 48.00)
118
+ ret["cfg"] = cfg
119
+ return ret, all_mkpq, all_mkpr, all_mkp3d, all_indices, num_matches
120
+
121
+
122
+ def main(dataset_dir, retrieval, features, matches, results, skip_matches=None):
123
+ assert retrieval.exists(), retrieval
124
+ assert features.exists(), features
125
+ assert matches.exists(), matches
126
+
127
+ retrieval_dict = parse_retrieval(retrieval)
128
+ queries = list(retrieval_dict.keys())
129
+
130
+ feature_file = h5py.File(features, "r", libver="latest")
131
+ match_file = h5py.File(matches, "r", libver="latest")
132
+
133
+ poses = {}
134
+ logs = {
135
+ "features": features,
136
+ "matches": matches,
137
+ "retrieval": retrieval,
138
+ "loc": {},
139
+ }
140
+ logger.info("Starting localization...")
141
+ for q in tqdm(queries):
142
+ db = retrieval_dict[q]
143
+ ret, mkpq, mkpr, mkp3d, indices, num_matches = pose_from_cluster(
144
+ dataset_dir, q, db, feature_file, match_file, skip_matches
145
+ )
146
+
147
+ poses[q] = (ret["qvec"], ret["tvec"])
148
+ logs["loc"][q] = {
149
+ "db": db,
150
+ "PnP_ret": ret,
151
+ "keypoints_query": mkpq,
152
+ "keypoints_db": mkpr,
153
+ "3d_points": mkp3d,
154
+ "indices_db": indices,
155
+ "num_matches": num_matches,
156
+ }
157
+
158
+ logger.info(f"Writing poses to {results}...")
159
+ with open(results, "w") as f:
160
+ for q in queries:
161
+ qvec, tvec = poses[q]
162
+ qvec = " ".join(map(str, qvec))
163
+ tvec = " ".join(map(str, tvec))
164
+ name = q.split("/")[-1]
165
+ f.write(f"{name} {qvec} {tvec}\n")
166
+
167
+ logs_path = f"{results}_logs.pkl"
168
+ logger.info(f"Writing logs to {logs_path}...")
169
+ with open(logs_path, "wb") as f:
170
+ pickle.dump(logs, f)
171
+ logger.info("Done!")
172
+
173
+
174
+ if __name__ == "__main__":
175
+ parser = argparse.ArgumentParser()
176
+ parser.add_argument("--dataset_dir", type=Path, required=True)
177
+ parser.add_argument("--retrieval", type=Path, required=True)
178
+ parser.add_argument("--features", type=Path, required=True)
179
+ parser.add_argument("--matches", type=Path, required=True)
180
+ parser.add_argument("--results", type=Path, required=True)
181
+ parser.add_argument("--skip_matches", type=int)
182
+ args = parser.parse_args()
183
+ main(**args.__dict__)
hloc/localize_sfm.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pickle
3
+ from collections import defaultdict
4
+ from pathlib import Path
5
+ from typing import Dict, List, Union
6
+
7
+ import numpy as np
8
+ import pycolmap
9
+ from tqdm import tqdm
10
+
11
+ from . import logger
12
+ from .utils.io import get_keypoints, get_matches
13
+ from .utils.parsers import parse_image_lists, parse_retrieval
14
+
15
+
16
+ def do_covisibility_clustering(
17
+ frame_ids: List[int], reconstruction: pycolmap.Reconstruction
18
+ ):
19
+ clusters = []
20
+ visited = set()
21
+ for frame_id in frame_ids:
22
+ # Check if already labeled
23
+ if frame_id in visited:
24
+ continue
25
+
26
+ # New component
27
+ clusters.append([])
28
+ queue = {frame_id}
29
+ while len(queue):
30
+ exploration_frame = queue.pop()
31
+
32
+ # Already part of the component
33
+ if exploration_frame in visited:
34
+ continue
35
+ visited.add(exploration_frame)
36
+ clusters[-1].append(exploration_frame)
37
+
38
+ observed = reconstruction.images[exploration_frame].points2D
39
+ connected_frames = {
40
+ obs.image_id
41
+ for p2D in observed
42
+ if p2D.has_point3D()
43
+ for obs in reconstruction.points3D[
44
+ p2D.point3D_id
45
+ ].track.elements
46
+ }
47
+ connected_frames &= set(frame_ids)
48
+ connected_frames -= visited
49
+ queue |= connected_frames
50
+
51
+ clusters = sorted(clusters, key=len, reverse=True)
52
+ return clusters
53
+
54
+
55
+ class QueryLocalizer:
56
+ def __init__(self, reconstruction, config=None):
57
+ self.reconstruction = reconstruction
58
+ self.config = config or {}
59
+
60
+ def localize(self, points2D_all, points2D_idxs, points3D_id, query_camera):
61
+ points2D = points2D_all[points2D_idxs]
62
+ points3D = [self.reconstruction.points3D[j].xyz for j in points3D_id]
63
+ ret = pycolmap.absolute_pose_estimation(
64
+ points2D,
65
+ points3D,
66
+ query_camera,
67
+ estimation_options=self.config.get("estimation", {}),
68
+ refinement_options=self.config.get("refinement", {}),
69
+ )
70
+ return ret
71
+
72
+
73
+ def pose_from_cluster(
74
+ localizer: QueryLocalizer,
75
+ qname: str,
76
+ query_camera: pycolmap.Camera,
77
+ db_ids: List[int],
78
+ features_path: Path,
79
+ matches_path: Path,
80
+ **kwargs,
81
+ ):
82
+ kpq = get_keypoints(features_path, qname)
83
+ kpq += 0.5 # COLMAP coordinates
84
+
85
+ kp_idx_to_3D = defaultdict(list)
86
+ kp_idx_to_3D_to_db = defaultdict(lambda: defaultdict(list))
87
+ num_matches = 0
88
+ for i, db_id in enumerate(db_ids):
89
+ image = localizer.reconstruction.images[db_id]
90
+ if image.num_points3D == 0:
91
+ logger.debug(f"No 3D points found for {image.name}.")
92
+ continue
93
+ points3D_ids = np.array(
94
+ [p.point3D_id if p.has_point3D() else -1 for p in image.points2D]
95
+ )
96
+
97
+ matches, _ = get_matches(matches_path, qname, image.name)
98
+ matches = matches[points3D_ids[matches[:, 1]] != -1]
99
+ num_matches += len(matches)
100
+ for idx, m in matches:
101
+ id_3D = points3D_ids[m]
102
+ kp_idx_to_3D_to_db[idx][id_3D].append(i)
103
+ # avoid duplicate observations
104
+ if id_3D not in kp_idx_to_3D[idx]:
105
+ kp_idx_to_3D[idx].append(id_3D)
106
+
107
+ idxs = list(kp_idx_to_3D.keys())
108
+ mkp_idxs = [i for i in idxs for _ in kp_idx_to_3D[i]]
109
+ mp3d_ids = [j for i in idxs for j in kp_idx_to_3D[i]]
110
+ ret = localizer.localize(kpq, mkp_idxs, mp3d_ids, query_camera, **kwargs)
111
+ if ret is not None:
112
+ ret["camera"] = query_camera
113
+
114
+ # mostly for logging and post-processing
115
+ mkp_to_3D_to_db = [
116
+ (j, kp_idx_to_3D_to_db[i][j]) for i in idxs for j in kp_idx_to_3D[i]
117
+ ]
118
+ log = {
119
+ "db": db_ids,
120
+ "PnP_ret": ret,
121
+ "keypoints_query": kpq[mkp_idxs],
122
+ "points3D_ids": mp3d_ids,
123
+ "points3D_xyz": None, # we don't log xyz anymore because of file size
124
+ "num_matches": num_matches,
125
+ "keypoint_index_to_db": (mkp_idxs, mkp_to_3D_to_db),
126
+ }
127
+ return ret, log
128
+
129
+
130
+ def main(
131
+ reference_sfm: Union[Path, pycolmap.Reconstruction],
132
+ queries: Path,
133
+ retrieval: Path,
134
+ features: Path,
135
+ matches: Path,
136
+ results: Path,
137
+ ransac_thresh: int = 12,
138
+ covisibility_clustering: bool = False,
139
+ prepend_camera_name: bool = False,
140
+ config: Dict = None,
141
+ ):
142
+ assert retrieval.exists(), retrieval
143
+ assert features.exists(), features
144
+ assert matches.exists(), matches
145
+
146
+ queries = parse_image_lists(queries, with_intrinsics=True)
147
+ retrieval_dict = parse_retrieval(retrieval)
148
+
149
+ logger.info("Reading the 3D model...")
150
+ if not isinstance(reference_sfm, pycolmap.Reconstruction):
151
+ reference_sfm = pycolmap.Reconstruction(reference_sfm)
152
+ db_name_to_id = {img.name: i for i, img in reference_sfm.images.items()}
153
+
154
+ config = {
155
+ "estimation": {"ransac": {"max_error": ransac_thresh}},
156
+ **(config or {}),
157
+ }
158
+ localizer = QueryLocalizer(reference_sfm, config)
159
+
160
+ cam_from_world = {}
161
+ logs = {
162
+ "features": features,
163
+ "matches": matches,
164
+ "retrieval": retrieval,
165
+ "loc": {},
166
+ }
167
+ logger.info("Starting localization...")
168
+ for qname, qcam in tqdm(queries):
169
+ if qname not in retrieval_dict:
170
+ logger.warning(
171
+ f"No images retrieved for query image {qname}. Skipping..."
172
+ )
173
+ continue
174
+ db_names = retrieval_dict[qname]
175
+ db_ids = []
176
+ for n in db_names:
177
+ if n not in db_name_to_id:
178
+ logger.warning(f"Image {n} was retrieved but not in database")
179
+ continue
180
+ db_ids.append(db_name_to_id[n])
181
+
182
+ if covisibility_clustering:
183
+ clusters = do_covisibility_clustering(db_ids, reference_sfm)
184
+ best_inliers = 0
185
+ best_cluster = None
186
+ logs_clusters = []
187
+ for i, cluster_ids in enumerate(clusters):
188
+ ret, log = pose_from_cluster(
189
+ localizer, qname, qcam, cluster_ids, features, matches
190
+ )
191
+ if ret is not None and ret["num_inliers"] > best_inliers:
192
+ best_cluster = i
193
+ best_inliers = ret["num_inliers"]
194
+ logs_clusters.append(log)
195
+ if best_cluster is not None:
196
+ ret = logs_clusters[best_cluster]["PnP_ret"]
197
+ cam_from_world[qname] = ret["cam_from_world"]
198
+ logs["loc"][qname] = {
199
+ "db": db_ids,
200
+ "best_cluster": best_cluster,
201
+ "log_clusters": logs_clusters,
202
+ "covisibility_clustering": covisibility_clustering,
203
+ }
204
+ else:
205
+ ret, log = pose_from_cluster(
206
+ localizer, qname, qcam, db_ids, features, matches
207
+ )
208
+ if ret is not None:
209
+ cam_from_world[qname] = ret["cam_from_world"]
210
+ else:
211
+ closest = reference_sfm.images[db_ids[0]]
212
+ cam_from_world[qname] = closest.cam_from_world
213
+ log["covisibility_clustering"] = covisibility_clustering
214
+ logs["loc"][qname] = log
215
+
216
+ logger.info(f"Localized {len(cam_from_world)} / {len(queries)} images.")
217
+ logger.info(f"Writing poses to {results}...")
218
+ with open(results, "w") as f:
219
+ for query, t in cam_from_world.items():
220
+ qvec = " ".join(map(str, t.rotation.quat[[3, 0, 1, 2]]))
221
+ tvec = " ".join(map(str, t.translation))
222
+ name = query.split("/")[-1]
223
+ if prepend_camera_name:
224
+ name = query.split("/")[-2] + "/" + name
225
+ f.write(f"{name} {qvec} {tvec}\n")
226
+
227
+ logs_path = f"{results}_logs.pkl"
228
+ logger.info(f"Writing logs to {logs_path}...")
229
+ # TODO: Resolve pickling issue with pycolmap objects.
230
+ with open(logs_path, "wb") as f:
231
+ pickle.dump(logs, f)
232
+ logger.info("Done!")
233
+
234
+
235
+ if __name__ == "__main__":
236
+ parser = argparse.ArgumentParser()
237
+ parser.add_argument("--reference_sfm", type=Path, required=True)
238
+ parser.add_argument("--queries", type=Path, required=True)
239
+ parser.add_argument("--features", type=Path, required=True)
240
+ parser.add_argument("--matches", type=Path, required=True)
241
+ parser.add_argument("--retrieval", type=Path, required=True)
242
+ parser.add_argument("--results", type=Path, required=True)
243
+ parser.add_argument("--ransac_thresh", type=float, default=12.0)
244
+ parser.add_argument("--covisibility_clustering", action="store_true")
245
+ parser.add_argument("--prepend_camera_name", action="store_true")
246
+ args = parser.parse_args()
247
+ main(**args.__dict__)
hloc/match_dense.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pprint
3
+ from collections import Counter, defaultdict
4
+ from itertools import chain
5
+ from pathlib import Path
6
+ from types import SimpleNamespace
7
+ from typing import Dict, Iterable, List, Optional, Set, Tuple, Union
8
+
9
+ import cv2
10
+ import h5py
11
+ import numpy as np
12
+ import torch
13
+ import torchvision.transforms.functional as F
14
+ from scipy.spatial import KDTree
15
+ from tqdm import tqdm
16
+
17
+ from . import logger, matchers
18
+ from .extract_features import read_image, resize_image
19
+ from .match_features import find_unique_new_pairs
20
+ from .utils.base_model import dynamic_load
21
+ from .utils.io import list_h5_names
22
+ from .utils.parsers import names_to_pair, parse_retrieval
23
+
24
+ device = "cuda" if torch.cuda.is_available() else "cpu"
25
+
26
+ confs = {
27
+ # Best quality but loads of points. Only use for small scenes
28
+ "loftr": {
29
+ "output": "matches-loftr",
30
+ "model": {
31
+ "name": "loftr",
32
+ "weights": "outdoor",
33
+ "max_keypoints": 2000,
34
+ "match_threshold": 0.2,
35
+ },
36
+ "preprocessing": {
37
+ "grayscale": True,
38
+ "resize_max": 1024,
39
+ "dfactor": 8,
40
+ "width": 640,
41
+ "height": 480,
42
+ "force_resize": True,
43
+ },
44
+ "max_error": 1, # max error for assigned keypoints (in px)
45
+ "cell_size": 1, # size of quantization patch (max 1 kp/patch)
46
+ },
47
+ "eloftr": {
48
+ "output": "matches-eloftr",
49
+ "model": {
50
+ "name": "eloftr",
51
+ "weights": "weights/eloftr_outdoor.ckpt",
52
+ "max_keypoints": 2000,
53
+ "match_threshold": 0.2,
54
+ },
55
+ "preprocessing": {
56
+ "grayscale": True,
57
+ "resize_max": 1024,
58
+ "dfactor": 32,
59
+ "width": 640,
60
+ "height": 480,
61
+ "force_resize": True,
62
+ },
63
+ "max_error": 1, # max error for assigned keypoints (in px)
64
+ "cell_size": 1, # size of quantization patch (max 1 kp/patch)
65
+ },
66
+ # "loftr_quadtree": {
67
+ # "output": "matches-loftr-quadtree",
68
+ # "model": {
69
+ # "name": "quadtree",
70
+ # "weights": "outdoor",
71
+ # "max_keypoints": 2000,
72
+ # "match_threshold": 0.2,
73
+ # },
74
+ # "preprocessing": {
75
+ # "grayscale": True,
76
+ # "resize_max": 1024,
77
+ # "dfactor": 8,
78
+ # "width": 640,
79
+ # "height": 480,
80
+ # "force_resize": True,
81
+ # },
82
+ # "max_error": 1, # max error for assigned keypoints (in px)
83
+ # "cell_size": 1, # size of quantization patch (max 1 kp/patch)
84
+ # },
85
+ "cotr": {
86
+ "output": "matches-cotr",
87
+ "model": {
88
+ "name": "cotr",
89
+ "weights": "out/default",
90
+ "max_keypoints": 2000,
91
+ "match_threshold": 0.2,
92
+ },
93
+ "preprocessing": {
94
+ "grayscale": False,
95
+ "resize_max": 1024,
96
+ "dfactor": 8,
97
+ "width": 640,
98
+ "height": 480,
99
+ "force_resize": True,
100
+ },
101
+ "max_error": 1, # max error for assigned keypoints (in px)
102
+ "cell_size": 1, # size of quantization patch (max 1 kp/patch)
103
+ },
104
+ # Semi-scalable loftr which limits detected keypoints
105
+ "loftr_aachen": {
106
+ "output": "matches-loftr_aachen",
107
+ "model": {
108
+ "name": "loftr",
109
+ "weights": "outdoor",
110
+ "max_keypoints": 2000,
111
+ "match_threshold": 0.2,
112
+ },
113
+ "preprocessing": {
114
+ "grayscale": True,
115
+ "resize_max": 1024,
116
+ "dfactor": 8,
117
+ "width": 640,
118
+ "height": 480,
119
+ "force_resize": True,
120
+ },
121
+ "max_error": 2, # max error for assigned keypoints (in px)
122
+ "cell_size": 8, # size of quantization patch (max 1 kp/patch)
123
+ },
124
+ # Use for matching superpoint feats with loftr
125
+ "loftr_superpoint": {
126
+ "output": "matches-loftr_aachen",
127
+ "model": {
128
+ "name": "loftr",
129
+ "weights": "outdoor",
130
+ "max_keypoints": 2000,
131
+ "match_threshold": 0.2,
132
+ },
133
+ "preprocessing": {
134
+ "grayscale": True,
135
+ "resize_max": 1024,
136
+ "dfactor": 8,
137
+ "width": 640,
138
+ "height": 480,
139
+ "force_resize": True,
140
+ },
141
+ "max_error": 4, # max error for assigned keypoints (in px)
142
+ "cell_size": 4, # size of quantization patch (max 1 kp/patch)
143
+ },
144
+ # Use topicfm for matching feats
145
+ "topicfm": {
146
+ "output": "matches-topicfm",
147
+ "model": {
148
+ "name": "topicfm",
149
+ "weights": "outdoor",
150
+ "max_keypoints": 2000,
151
+ "match_threshold": 0.2,
152
+ },
153
+ "preprocessing": {
154
+ "grayscale": True,
155
+ "force_resize": True,
156
+ "resize_max": 1024,
157
+ "dfactor": 8,
158
+ "width": 640,
159
+ "height": 480,
160
+ },
161
+ },
162
+ # Use aspanformer for matching feats
163
+ "aspanformer": {
164
+ "output": "matches-aspanformer",
165
+ "model": {
166
+ "name": "aspanformer",
167
+ "weights": "outdoor",
168
+ "max_keypoints": 2000,
169
+ "match_threshold": 0.2,
170
+ },
171
+ "preprocessing": {
172
+ "grayscale": True,
173
+ "force_resize": True,
174
+ "resize_max": 1024,
175
+ "width": 640,
176
+ "height": 480,
177
+ "dfactor": 8,
178
+ },
179
+ },
180
+ "duster": {
181
+ "output": "matches-duster",
182
+ "model": {
183
+ "name": "duster",
184
+ "weights": "vit_large",
185
+ "max_keypoints": 2000,
186
+ "match_threshold": 0.2,
187
+ },
188
+ "preprocessing": {
189
+ "grayscale": False,
190
+ "resize_max": 512,
191
+ "dfactor": 16,
192
+ },
193
+ },
194
+ "mast3r": {
195
+ "output": "matches-mast3r",
196
+ "model": {
197
+ "name": "mast3r",
198
+ "weights": "vit_large",
199
+ "max_keypoints": 2000,
200
+ "match_threshold": 0.2,
201
+ },
202
+ "preprocessing": {
203
+ "grayscale": False,
204
+ "resize_max": 512,
205
+ "dfactor": 16,
206
+ },
207
+ },
208
+ "xfeat_lightglue": {
209
+ "output": "matches-xfeat_lightglue",
210
+ "model": {
211
+ "name": "xfeat_lightglue",
212
+ "max_keypoints": 8000,
213
+ },
214
+ "preprocessing": {
215
+ "grayscale": False,
216
+ "force_resize": False,
217
+ "resize_max": 1024,
218
+ "width": 640,
219
+ "height": 480,
220
+ "dfactor": 8,
221
+ },
222
+ },
223
+ "xfeat_dense": {
224
+ "output": "matches-xfeat_dense",
225
+ "model": {
226
+ "name": "xfeat_dense",
227
+ "max_keypoints": 8000,
228
+ },
229
+ "preprocessing": {
230
+ "grayscale": False,
231
+ "force_resize": False,
232
+ "resize_max": 1024,
233
+ "width": 640,
234
+ "height": 480,
235
+ "dfactor": 8,
236
+ },
237
+ },
238
+ "dkm": {
239
+ "output": "matches-dkm",
240
+ "model": {
241
+ "name": "dkm",
242
+ "weights": "outdoor",
243
+ "max_keypoints": 2000,
244
+ "match_threshold": 0.2,
245
+ },
246
+ "preprocessing": {
247
+ "grayscale": False,
248
+ "force_resize": True,
249
+ "resize_max": 1024,
250
+ "width": 80,
251
+ "height": 60,
252
+ "dfactor": 8,
253
+ },
254
+ },
255
+ "roma": {
256
+ "output": "matches-roma",
257
+ "model": {
258
+ "name": "roma",
259
+ "weights": "outdoor",
260
+ "max_keypoints": 2000,
261
+ "match_threshold": 0.2,
262
+ },
263
+ "preprocessing": {
264
+ "grayscale": False,
265
+ "force_resize": True,
266
+ "resize_max": 1024,
267
+ "width": 320,
268
+ "height": 240,
269
+ "dfactor": 8,
270
+ },
271
+ },
272
+ "gim(dkm)": {
273
+ "output": "matches-gim",
274
+ "model": {
275
+ "name": "gim",
276
+ "weights": "gim_dkm_100h.ckpt",
277
+ "max_keypoints": 2000,
278
+ "match_threshold": 0.2,
279
+ },
280
+ "preprocessing": {
281
+ "grayscale": False,
282
+ "force_resize": True,
283
+ "resize_max": 1024,
284
+ "width": 320,
285
+ "height": 240,
286
+ "dfactor": 8,
287
+ },
288
+ },
289
+ "omniglue": {
290
+ "output": "matches-omniglue",
291
+ "model": {
292
+ "name": "omniglue",
293
+ "match_threshold": 0.2,
294
+ "max_keypoints": 2000,
295
+ "features": "null",
296
+ },
297
+ "preprocessing": {
298
+ "grayscale": False,
299
+ "resize_max": 1024,
300
+ "dfactor": 8,
301
+ "force_resize": False,
302
+ "resize_max": 1024,
303
+ "width": 640,
304
+ "height": 480,
305
+ "dfactor": 8,
306
+ },
307
+ },
308
+ "sold2": {
309
+ "output": "matches-sold2",
310
+ "model": {
311
+ "name": "sold2",
312
+ "max_keypoints": 2000,
313
+ "match_threshold": 0.2,
314
+ },
315
+ "preprocessing": {
316
+ "grayscale": True,
317
+ "force_resize": True,
318
+ "resize_max": 1024,
319
+ "width": 640,
320
+ "height": 480,
321
+ "dfactor": 8,
322
+ },
323
+ },
324
+ "gluestick": {
325
+ "output": "matches-gluestick",
326
+ "model": {
327
+ "name": "gluestick",
328
+ "use_lines": True,
329
+ "max_keypoints": 1000,
330
+ "max_lines": 300,
331
+ "force_num_keypoints": False,
332
+ },
333
+ "preprocessing": {
334
+ "grayscale": True,
335
+ "force_resize": True,
336
+ "resize_max": 1024,
337
+ "width": 640,
338
+ "height": 480,
339
+ "dfactor": 8,
340
+ },
341
+ },
342
+ }
343
+
344
+
345
+ def to_cpts(kpts, ps):
346
+ if ps > 0.0:
347
+ kpts = np.round(np.round((kpts + 0.5) / ps) * ps - 0.5, 2)
348
+ return [tuple(cpt) for cpt in kpts]
349
+
350
+
351
+ def assign_keypoints(
352
+ kpts: np.ndarray,
353
+ other_cpts: Union[List[Tuple], np.ndarray],
354
+ max_error: float,
355
+ update: bool = False,
356
+ ref_bins: Optional[List[Counter]] = None,
357
+ scores: Optional[np.ndarray] = None,
358
+ cell_size: Optional[int] = None,
359
+ ):
360
+ if not update:
361
+ # Without update this is just a NN search
362
+ if len(other_cpts) == 0 or len(kpts) == 0:
363
+ return np.full(len(kpts), -1)
364
+ dist, kpt_ids = KDTree(np.array(other_cpts)).query(kpts)
365
+ valid = dist <= max_error
366
+ kpt_ids[~valid] = -1
367
+ return kpt_ids
368
+ else:
369
+ ps = cell_size if cell_size is not None else max_error
370
+ ps = max(ps, max_error)
371
+ # With update we quantize and bin (optionally)
372
+ assert isinstance(other_cpts, list)
373
+ kpt_ids = []
374
+ cpts = to_cpts(kpts, ps)
375
+ bpts = to_cpts(kpts, int(max_error))
376
+ cp_to_id = {val: i for i, val in enumerate(other_cpts)}
377
+ for i, (cpt, bpt) in enumerate(zip(cpts, bpts)):
378
+ try:
379
+ kid = cp_to_id[cpt]
380
+ except KeyError:
381
+ kid = len(cp_to_id)
382
+ cp_to_id[cpt] = kid
383
+ other_cpts.append(cpt)
384
+ if ref_bins is not None:
385
+ ref_bins.append(Counter())
386
+ if ref_bins is not None:
387
+ score = scores[i] if scores is not None else 1
388
+ ref_bins[cp_to_id[cpt]][bpt] += score
389
+ kpt_ids.append(kid)
390
+ return np.array(kpt_ids)
391
+
392
+
393
+ def get_grouped_ids(array):
394
+ # Group array indices based on its values
395
+ # all duplicates are grouped as a set
396
+ idx_sort = np.argsort(array)
397
+ sorted_array = array[idx_sort]
398
+ _, ids, _ = np.unique(sorted_array, return_counts=True, return_index=True)
399
+ res = np.split(idx_sort, ids[1:])
400
+ return res
401
+
402
+
403
+ def get_unique_matches(match_ids, scores):
404
+ if len(match_ids.shape) == 1:
405
+ return [0]
406
+
407
+ isets1 = get_grouped_ids(match_ids[:, 0])
408
+ isets2 = get_grouped_ids(match_ids[:, 1])
409
+ uid1s = [ids[scores[ids].argmax()] for ids in isets1 if len(ids) > 0]
410
+ uid2s = [ids[scores[ids].argmax()] for ids in isets2 if len(ids) > 0]
411
+ uids = list(set(uid1s).intersection(uid2s))
412
+ return match_ids[uids], scores[uids]
413
+
414
+
415
+ def matches_to_matches0(matches, scores):
416
+ if len(matches) == 0:
417
+ return np.zeros(0, dtype=np.int32), np.zeros(0, dtype=np.float16)
418
+ n_kps0 = np.max(matches[:, 0]) + 1
419
+ matches0 = -np.ones((n_kps0,))
420
+ scores0 = np.zeros((n_kps0,))
421
+ matches0[matches[:, 0]] = matches[:, 1]
422
+ scores0[matches[:, 0]] = scores
423
+ return matches0.astype(np.int32), scores0.astype(np.float16)
424
+
425
+
426
+ def kpids_to_matches0(kpt_ids0, kpt_ids1, scores):
427
+ valid = (kpt_ids0 != -1) & (kpt_ids1 != -1)
428
+ matches = np.dstack([kpt_ids0[valid], kpt_ids1[valid]])
429
+ matches = matches.reshape(-1, 2)
430
+ scores = scores[valid]
431
+
432
+ # Remove n-to-1 matches
433
+ matches, scores = get_unique_matches(matches, scores)
434
+ return matches_to_matches0(matches, scores)
435
+
436
+
437
+ def scale_keypoints(kpts, scale):
438
+ if np.any(scale != 1.0):
439
+ kpts *= kpts.new_tensor(scale)
440
+ return kpts
441
+
442
+
443
+ class ImagePairDataset(torch.utils.data.Dataset):
444
+ default_conf = {
445
+ "grayscale": True,
446
+ "resize_max": 1024,
447
+ "dfactor": 8,
448
+ "cache_images": False,
449
+ }
450
+
451
+ def __init__(self, image_dir, conf, pairs):
452
+ self.image_dir = image_dir
453
+ self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf})
454
+ self.pairs = pairs
455
+ if self.conf.cache_images:
456
+ image_names = set(sum(pairs, ())) # unique image names in pairs
457
+ logger.info(
458
+ f"Loading and caching {len(image_names)} unique images."
459
+ )
460
+ self.images = {}
461
+ self.scales = {}
462
+ for name in tqdm(image_names):
463
+ image = read_image(self.image_dir / name, self.conf.grayscale)
464
+ self.images[name], self.scales[name] = self.preprocess(image)
465
+
466
+ def preprocess(self, image: np.ndarray):
467
+ image = image.astype(np.float32, copy=False)
468
+ size = image.shape[:2][::-1]
469
+ scale = np.array([1.0, 1.0])
470
+
471
+ if self.conf.resize_max:
472
+ scale = self.conf.resize_max / max(size)
473
+ if scale < 1.0:
474
+ size_new = tuple(int(round(x * scale)) for x in size)
475
+ image = resize_image(image, size_new, "cv2_area")
476
+ scale = np.array(size) / np.array(size_new)
477
+
478
+ if self.conf.grayscale:
479
+ assert image.ndim == 2, image.shape
480
+ image = image[None]
481
+ else:
482
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
483
+ image = torch.from_numpy(image / 255.0).float()
484
+
485
+ # assure that the size is divisible by dfactor
486
+ size_new = tuple(
487
+ map(
488
+ lambda x: int(x // self.conf.dfactor * self.conf.dfactor),
489
+ image.shape[-2:],
490
+ )
491
+ )
492
+ image = F.resize(image, size=size_new)
493
+ scale = np.array(size) / np.array(size_new)[::-1]
494
+ return image, scale
495
+
496
+ def __len__(self):
497
+ return len(self.pairs)
498
+
499
+ def __getitem__(self, idx):
500
+ name0, name1 = self.pairs[idx]
501
+ if self.conf.cache_images:
502
+ image0, scale0 = self.images[name0], self.scales[name0]
503
+ image1, scale1 = self.images[name1], self.scales[name1]
504
+ else:
505
+ image0 = read_image(self.image_dir / name0, self.conf.grayscale)
506
+ image1 = read_image(self.image_dir / name1, self.conf.grayscale)
507
+ image0, scale0 = self.preprocess(image0)
508
+ image1, scale1 = self.preprocess(image1)
509
+ return image0, image1, scale0, scale1, name0, name1
510
+
511
+
512
+ @torch.no_grad()
513
+ def match_dense(
514
+ conf: Dict,
515
+ pairs: List[Tuple[str, str]],
516
+ image_dir: Path,
517
+ match_path: Path, # out
518
+ existing_refs: Optional[List] = [],
519
+ ):
520
+ device = "cuda" if torch.cuda.is_available() else "cpu"
521
+ Model = dynamic_load(matchers, conf["model"]["name"])
522
+ model = Model(conf["model"]).eval().to(device)
523
+
524
+ dataset = ImagePairDataset(image_dir, conf["preprocessing"], pairs)
525
+ loader = torch.utils.data.DataLoader(
526
+ dataset, num_workers=16, batch_size=1, shuffle=False
527
+ )
528
+
529
+ logger.info("Performing dense matching...")
530
+ with h5py.File(str(match_path), "a") as fd:
531
+ for data in tqdm(loader, smoothing=0.1):
532
+ # load image-pair data
533
+ image0, image1, scale0, scale1, (name0,), (name1,) = data
534
+ scale0, scale1 = scale0[0].numpy(), scale1[0].numpy()
535
+ image0, image1 = image0.to(device), image1.to(device)
536
+
537
+ # match semi-dense
538
+ # for consistency with pairs_from_*: refine kpts of image0
539
+ if name0 in existing_refs:
540
+ # special case: flip to enable refinement in query image
541
+ pred = model({"image0": image1, "image1": image0})
542
+ pred = {
543
+ **pred,
544
+ "keypoints0": pred["keypoints1"],
545
+ "keypoints1": pred["keypoints0"],
546
+ }
547
+ else:
548
+ # usual case
549
+ pred = model({"image0": image0, "image1": image1})
550
+
551
+ # Rescale keypoints and move to cpu
552
+ kpts0, kpts1 = pred["keypoints0"], pred["keypoints1"]
553
+ kpts0 = scale_keypoints(kpts0 + 0.5, scale0) - 0.5
554
+ kpts1 = scale_keypoints(kpts1 + 0.5, scale1) - 0.5
555
+ kpts0 = kpts0.cpu().numpy()
556
+ kpts1 = kpts1.cpu().numpy()
557
+ scores = pred["scores"].cpu().numpy()
558
+
559
+ # Write matches and matching scores in hloc format
560
+ pair = names_to_pair(name0, name1)
561
+ if pair in fd:
562
+ del fd[pair]
563
+ grp = fd.create_group(pair)
564
+
565
+ # Write dense matching output
566
+ grp.create_dataset("keypoints0", data=kpts0)
567
+ grp.create_dataset("keypoints1", data=kpts1)
568
+ grp.create_dataset("scores", data=scores)
569
+ del model, loader
570
+
571
+
572
+ # default: quantize all!
573
+ def load_keypoints(
574
+ conf: Dict, feature_paths_refs: List[Path], quantize: Optional[set] = None
575
+ ):
576
+ name2ref = {
577
+ n: i for i, p in enumerate(feature_paths_refs) for n in list_h5_names(p)
578
+ }
579
+
580
+ existing_refs = set(name2ref.keys())
581
+ if quantize is None:
582
+ quantize = existing_refs # quantize all
583
+ if len(existing_refs) > 0:
584
+ logger.info(f"Loading keypoints from {len(existing_refs)} images.")
585
+
586
+ # Load query keypoints
587
+ cpdict = defaultdict(list)
588
+ bindict = defaultdict(list)
589
+ for name in existing_refs:
590
+ with h5py.File(str(feature_paths_refs[name2ref[name]]), "r") as fd:
591
+ kps = fd[name]["keypoints"].__array__()
592
+ if name not in quantize:
593
+ cpdict[name] = kps
594
+ else:
595
+ if "scores" in fd[name].keys():
596
+ kp_scores = fd[name]["scores"].__array__()
597
+ else:
598
+ # we set the score to 1.0 if not provided
599
+ # increase for more weight on reference keypoints for
600
+ # stronger anchoring
601
+ kp_scores = [1.0 for _ in range(kps.shape[0])]
602
+ # bin existing keypoints of reference images for association
603
+ assign_keypoints(
604
+ kps,
605
+ cpdict[name],
606
+ conf["max_error"],
607
+ True,
608
+ bindict[name],
609
+ kp_scores,
610
+ conf["cell_size"],
611
+ )
612
+ return cpdict, bindict
613
+
614
+
615
+ def aggregate_matches(
616
+ conf: Dict,
617
+ pairs: List[Tuple[str, str]],
618
+ match_path: Path,
619
+ feature_path: Path,
620
+ required_queries: Optional[Set[str]] = None,
621
+ max_kps: Optional[int] = None,
622
+ cpdict: Dict[str, Iterable] = defaultdict(list),
623
+ bindict: Dict[str, List[Counter]] = defaultdict(list),
624
+ ):
625
+ if required_queries is None:
626
+ required_queries = set(sum(pairs, ()))
627
+ # default: do not overwrite existing features in feature_path!
628
+ required_queries -= set(list_h5_names(feature_path))
629
+
630
+ # if an entry in cpdict is provided as np.ndarray we assume it is fixed
631
+ required_queries -= set(
632
+ [k for k, v in cpdict.items() if isinstance(v, np.ndarray)]
633
+ )
634
+
635
+ # sort pairs for reduced RAM
636
+ pairs_per_q = Counter(list(chain(*pairs)))
637
+ pairs_score = [min(pairs_per_q[i], pairs_per_q[j]) for i, j in pairs]
638
+ pairs = [p for _, p in sorted(zip(pairs_score, pairs))]
639
+
640
+ if len(required_queries) > 0:
641
+ logger.info(
642
+ f"Aggregating keypoints for {len(required_queries)} images."
643
+ )
644
+ n_kps = 0
645
+ with h5py.File(str(match_path), "a") as fd:
646
+ for name0, name1 in tqdm(pairs, smoothing=0.1):
647
+ pair = names_to_pair(name0, name1)
648
+ grp = fd[pair]
649
+ kpts0 = grp["keypoints0"].__array__()
650
+ kpts1 = grp["keypoints1"].__array__()
651
+ scores = grp["scores"].__array__()
652
+
653
+ # Aggregate local features
654
+ update0 = name0 in required_queries
655
+ update1 = name1 in required_queries
656
+
657
+ # in localization we do not want to bin the query kp
658
+ # assumes that the query is name0!
659
+ if update0 and not update1 and max_kps is None:
660
+ max_error0 = cell_size0 = 0.0
661
+ else:
662
+ max_error0 = conf["max_error"]
663
+ cell_size0 = conf["cell_size"]
664
+
665
+ # Get match ids and extend query keypoints (cpdict)
666
+ mkp_ids0 = assign_keypoints(
667
+ kpts0,
668
+ cpdict[name0],
669
+ max_error0,
670
+ update0,
671
+ bindict[name0],
672
+ scores,
673
+ cell_size0,
674
+ )
675
+ mkp_ids1 = assign_keypoints(
676
+ kpts1,
677
+ cpdict[name1],
678
+ conf["max_error"],
679
+ update1,
680
+ bindict[name1],
681
+ scores,
682
+ conf["cell_size"],
683
+ )
684
+
685
+ # Build matches from assignments
686
+ matches0, scores0 = kpids_to_matches0(mkp_ids0, mkp_ids1, scores)
687
+
688
+ assert kpts0.shape[0] == scores.shape[0]
689
+ grp.create_dataset("matches0", data=matches0)
690
+ grp.create_dataset("matching_scores0", data=scores0)
691
+
692
+ # Convert bins to kps if finished, and store them
693
+ for name in (name0, name1):
694
+ pairs_per_q[name] -= 1
695
+ if pairs_per_q[name] > 0 or name not in required_queries:
696
+ continue
697
+ kp_score = [c.most_common(1)[0][1] for c in bindict[name]]
698
+ cpdict[name] = [c.most_common(1)[0][0] for c in bindict[name]]
699
+ cpdict[name] = np.array(cpdict[name], dtype=np.float32)
700
+
701
+ # Select top-k query kps by score (reassign matches later)
702
+ if max_kps:
703
+ top_k = min(max_kps, cpdict[name].shape[0])
704
+ top_k = np.argsort(kp_score)[::-1][:top_k]
705
+ cpdict[name] = cpdict[name][top_k]
706
+ kp_score = np.array(kp_score)[top_k]
707
+
708
+ # Write query keypoints
709
+ with h5py.File(feature_path, "a") as kfd:
710
+ if name in kfd:
711
+ del kfd[name]
712
+ kgrp = kfd.create_group(name)
713
+ kgrp.create_dataset("keypoints", data=cpdict[name])
714
+ kgrp.create_dataset("score", data=kp_score)
715
+ n_kps += cpdict[name].shape[0]
716
+ del bindict[name]
717
+
718
+ if len(required_queries) > 0:
719
+ avg_kp_per_image = round(n_kps / len(required_queries), 1)
720
+ logger.info(
721
+ f"Finished assignment, found {avg_kp_per_image} "
722
+ f"keypoints/image (avg.), total {n_kps}."
723
+ )
724
+ return cpdict
725
+
726
+
727
+ def assign_matches(
728
+ pairs: List[Tuple[str, str]],
729
+ match_path: Path,
730
+ keypoints: Union[List[Path], Dict[str, np.array]],
731
+ max_error: float,
732
+ ):
733
+ if isinstance(keypoints, list):
734
+ keypoints = load_keypoints({}, keypoints, kpts_as_bin=set([]))
735
+ assert len(set(sum(pairs, ())) - set(keypoints.keys())) == 0
736
+ with h5py.File(str(match_path), "a") as fd:
737
+ for name0, name1 in tqdm(pairs):
738
+ pair = names_to_pair(name0, name1)
739
+ grp = fd[pair]
740
+ kpts0 = grp["keypoints0"].__array__()
741
+ kpts1 = grp["keypoints1"].__array__()
742
+ scores = grp["scores"].__array__()
743
+
744
+ # NN search across cell boundaries
745
+ mkp_ids0 = assign_keypoints(kpts0, keypoints[name0], max_error)
746
+ mkp_ids1 = assign_keypoints(kpts1, keypoints[name1], max_error)
747
+
748
+ matches0, scores0 = kpids_to_matches0(mkp_ids0, mkp_ids1, scores)
749
+
750
+ # overwrite matches0 and matching_scores0
751
+ del grp["matches0"], grp["matching_scores0"]
752
+ grp.create_dataset("matches0", data=matches0)
753
+ grp.create_dataset("matching_scores0", data=scores0)
754
+
755
+
756
+ @torch.no_grad()
757
+ def match_and_assign(
758
+ conf: Dict,
759
+ pairs_path: Path,
760
+ image_dir: Path,
761
+ match_path: Path, # out
762
+ feature_path_q: Path, # out
763
+ feature_paths_refs: Optional[List[Path]] = [],
764
+ max_kps: Optional[int] = 8192,
765
+ overwrite: bool = False,
766
+ ) -> Path:
767
+ for path in feature_paths_refs:
768
+ if not path.exists():
769
+ raise FileNotFoundError(f"Reference feature file {path}.")
770
+ pairs = parse_retrieval(pairs_path)
771
+ pairs = [(q, r) for q, rs in pairs.items() for r in rs]
772
+ pairs = find_unique_new_pairs(pairs, None if overwrite else match_path)
773
+ required_queries = set(sum(pairs, ()))
774
+
775
+ name2ref = {
776
+ n: i for i, p in enumerate(feature_paths_refs) for n in list_h5_names(p)
777
+ }
778
+ existing_refs = required_queries.intersection(set(name2ref.keys()))
779
+
780
+ # images which require feature extraction
781
+ required_queries = required_queries - existing_refs
782
+
783
+ if feature_path_q.exists():
784
+ existing_queries = set(list_h5_names(feature_path_q))
785
+ feature_paths_refs.append(feature_path_q)
786
+ existing_refs = set.union(existing_refs, existing_queries)
787
+ if not overwrite:
788
+ required_queries = required_queries - existing_queries
789
+
790
+ if len(pairs) == 0 and len(required_queries) == 0:
791
+ logger.info("All pairs exist. Skipping dense matching.")
792
+ return
793
+
794
+ # extract semi-dense matches
795
+ match_dense(conf, pairs, image_dir, match_path, existing_refs=existing_refs)
796
+
797
+ logger.info("Assigning matches...")
798
+
799
+ # Pre-load existing keypoints
800
+ cpdict, bindict = load_keypoints(
801
+ conf, feature_paths_refs, quantize=required_queries
802
+ )
803
+
804
+ # Reassign matches by aggregation
805
+ cpdict = aggregate_matches(
806
+ conf,
807
+ pairs,
808
+ match_path,
809
+ feature_path=feature_path_q,
810
+ required_queries=required_queries,
811
+ max_kps=max_kps,
812
+ cpdict=cpdict,
813
+ bindict=bindict,
814
+ )
815
+
816
+ # Invalidate matches that are far from selected bin by reassignment
817
+ if max_kps is not None:
818
+ logger.info(f'Reassign matches with max_error={conf["max_error"]}.')
819
+ assign_matches(pairs, match_path, cpdict, max_error=conf["max_error"])
820
+
821
+
822
+ def scale_lines(lines, scale):
823
+ if np.any(scale != 1.0):
824
+ lines *= lines.new_tensor(scale)
825
+ return lines
826
+
827
+
828
+ def match(model, path_0, path_1, conf):
829
+ default_conf = {
830
+ "grayscale": True,
831
+ "resize_max": 1024,
832
+ "dfactor": 8,
833
+ "cache_images": False,
834
+ "force_resize": False,
835
+ "width": 320,
836
+ "height": 240,
837
+ }
838
+
839
+ def preprocess(image: np.ndarray):
840
+ image = image.astype(np.float32, copy=False)
841
+ size = image.shape[:2][::-1]
842
+ scale = np.array([1.0, 1.0])
843
+ if conf.resize_max:
844
+ scale = conf.resize_max / max(size)
845
+ if scale < 1.0:
846
+ size_new = tuple(int(round(x * scale)) for x in size)
847
+ image = resize_image(image, size_new, "cv2_area")
848
+ scale = np.array(size) / np.array(size_new)
849
+ if conf.force_resize:
850
+ size = image.shape[:2][::-1]
851
+ image = resize_image(image, (conf.width, conf.height), "cv2_area")
852
+ size_new = (conf.width, conf.height)
853
+ scale = np.array(size) / np.array(size_new)
854
+ if conf.grayscale:
855
+ assert image.ndim == 2, image.shape
856
+ image = image[None]
857
+ else:
858
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
859
+ image = torch.from_numpy(image / 255.0).float()
860
+ # assure that the size is divisible by dfactor
861
+ size_new = tuple(
862
+ map(
863
+ lambda x: int(x // conf.dfactor * conf.dfactor),
864
+ image.shape[-2:],
865
+ )
866
+ )
867
+ image = F.resize(image, size=size_new, antialias=True)
868
+ scale = np.array(size) / np.array(size_new)[::-1]
869
+ return image, scale
870
+
871
+ conf = SimpleNamespace(**{**default_conf, **conf})
872
+ image0 = read_image(path_0, conf.grayscale)
873
+ image1 = read_image(path_1, conf.grayscale)
874
+ image0, scale0 = preprocess(image0)
875
+ image1, scale1 = preprocess(image1)
876
+ image0 = image0.to(device)[None]
877
+ image1 = image1.to(device)[None]
878
+ pred = model({"image0": image0, "image1": image1})
879
+
880
+ # Rescale keypoints and move to cpu
881
+ kpts0, kpts1 = pred["keypoints0"], pred["keypoints1"]
882
+ kpts0 = scale_keypoints(kpts0 + 0.5, scale0) - 0.5
883
+ kpts1 = scale_keypoints(kpts1 + 0.5, scale1) - 0.5
884
+
885
+ ret = {
886
+ "image0": image0.squeeze().cpu().numpy(),
887
+ "image1": image1.squeeze().cpu().numpy(),
888
+ "keypoints0": kpts0.cpu().numpy(),
889
+ "keypoints1": kpts1.cpu().numpy(),
890
+ }
891
+ if "mconf" in pred.keys():
892
+ ret["mconf"] = pred["mconf"].cpu().numpy()
893
+ return ret
894
+
895
+
896
+ @torch.no_grad()
897
+ def match_images(model, image_0, image_1, conf, device="cpu"):
898
+ default_conf = {
899
+ "grayscale": True,
900
+ "resize_max": 1024,
901
+ "dfactor": 8,
902
+ "cache_images": False,
903
+ "force_resize": False,
904
+ "width": 320,
905
+ "height": 240,
906
+ }
907
+
908
+ def preprocess(image: np.ndarray):
909
+ image = image.astype(np.float32, copy=False)
910
+ size = image.shape[:2][::-1]
911
+ scale = np.array([1.0, 1.0])
912
+ if conf.resize_max:
913
+ scale = conf.resize_max / max(size)
914
+ if scale < 1.0:
915
+ size_new = tuple(int(round(x * scale)) for x in size)
916
+ image = resize_image(image, size_new, "cv2_area")
917
+ scale = np.array(size) / np.array(size_new)
918
+ if conf.force_resize:
919
+ size = image.shape[:2][::-1]
920
+ image = resize_image(image, (conf.width, conf.height), "cv2_area")
921
+ size_new = (conf.width, conf.height)
922
+ scale = np.array(size) / np.array(size_new)
923
+ if conf.grayscale:
924
+ assert image.ndim == 2, image.shape
925
+ image = image[None]
926
+ else:
927
+ image = image.transpose((2, 0, 1)) # HxWxC to CxHxW
928
+ image = torch.from_numpy(image / 255.0).float()
929
+
930
+ # assure that the size is divisible by dfactor
931
+ size_new = tuple(
932
+ map(
933
+ lambda x: int(x // conf.dfactor * conf.dfactor),
934
+ image.shape[-2:],
935
+ )
936
+ )
937
+ image = F.resize(image, size=size_new)
938
+ scale = np.array(size) / np.array(size_new)[::-1]
939
+ return image, scale
940
+
941
+ conf = SimpleNamespace(**{**default_conf, **conf})
942
+
943
+ if len(image_0.shape) == 3 and conf.grayscale:
944
+ image0 = cv2.cvtColor(image_0, cv2.COLOR_RGB2GRAY)
945
+ else:
946
+ image0 = image_0
947
+ if len(image_0.shape) == 3 and conf.grayscale:
948
+ image1 = cv2.cvtColor(image_1, cv2.COLOR_RGB2GRAY)
949
+ else:
950
+ image1 = image_1
951
+
952
+ # comment following lines, image is always RGB mode
953
+ # if not conf.grayscale and len(image0.shape) == 3:
954
+ # image0 = image0[:, :, ::-1] # BGR to RGB
955
+ # if not conf.grayscale and len(image1.shape) == 3:
956
+ # image1 = image1[:, :, ::-1] # BGR to RGB
957
+
958
+ image0, scale0 = preprocess(image0)
959
+ image1, scale1 = preprocess(image1)
960
+ image0 = image0.to(device)[None]
961
+ image1 = image1.to(device)[None]
962
+ pred = model({"image0": image0, "image1": image1})
963
+
964
+ s0 = np.array(image_0.shape[:2][::-1]) / np.array(image0.shape[-2:][::-1])
965
+ s1 = np.array(image_1.shape[:2][::-1]) / np.array(image1.shape[-2:][::-1])
966
+
967
+ # Rescale keypoints and move to cpu
968
+ if "keypoints0" in pred.keys() and "keypoints1" in pred.keys():
969
+ kpts0, kpts1 = pred["keypoints0"], pred["keypoints1"]
970
+ kpts0_origin = scale_keypoints(kpts0 + 0.5, s0) - 0.5
971
+ kpts1_origin = scale_keypoints(kpts1 + 0.5, s1) - 0.5
972
+
973
+ ret = {
974
+ "image0": image0.squeeze().cpu().numpy(),
975
+ "image1": image1.squeeze().cpu().numpy(),
976
+ "image0_orig": image_0,
977
+ "image1_orig": image_1,
978
+ "keypoints0": kpts0.cpu().numpy(),
979
+ "keypoints1": kpts1.cpu().numpy(),
980
+ "keypoints0_orig": kpts0_origin.cpu().numpy(),
981
+ "keypoints1_orig": kpts1_origin.cpu().numpy(),
982
+ "mkeypoints0": kpts0.cpu().numpy(),
983
+ "mkeypoints1": kpts1.cpu().numpy(),
984
+ "mkeypoints0_orig": kpts0_origin.cpu().numpy(),
985
+ "mkeypoints1_orig": kpts1_origin.cpu().numpy(),
986
+ "original_size0": np.array(image_0.shape[:2][::-1]),
987
+ "original_size1": np.array(image_1.shape[:2][::-1]),
988
+ "new_size0": np.array(image0.shape[-2:][::-1]),
989
+ "new_size1": np.array(image1.shape[-2:][::-1]),
990
+ "scale0": s0,
991
+ "scale1": s1,
992
+ }
993
+ if "mconf" in pred.keys():
994
+ ret["mconf"] = pred["mconf"].cpu().numpy()
995
+ elif "scores" in pred.keys(): # adapting loftr
996
+ ret["mconf"] = pred["scores"].cpu().numpy()
997
+ else:
998
+ ret["mconf"] = np.ones_like(kpts0.cpu().numpy()[:, 0])
999
+ if "lines0" in pred.keys() and "lines1" in pred.keys():
1000
+ if "keypoints0" in pred.keys() and "keypoints1" in pred.keys():
1001
+ kpts0, kpts1 = pred["keypoints0"], pred["keypoints1"]
1002
+ kpts0_origin = scale_keypoints(kpts0 + 0.5, s0) - 0.5
1003
+ kpts1_origin = scale_keypoints(kpts1 + 0.5, s1) - 0.5
1004
+ kpts0_origin = kpts0_origin.cpu().numpy()
1005
+ kpts1_origin = kpts1_origin.cpu().numpy()
1006
+ else:
1007
+ kpts0_origin, kpts1_origin = (
1008
+ None,
1009
+ None,
1010
+ ) # np.zeros([0]), np.zeros([0])
1011
+ lines0, lines1 = pred["lines0"], pred["lines1"]
1012
+ lines0_raw, lines1_raw = pred["raw_lines0"], pred["raw_lines1"]
1013
+
1014
+ lines0_raw = torch.from_numpy(lines0_raw.copy())
1015
+ lines1_raw = torch.from_numpy(lines1_raw.copy())
1016
+ lines0_raw = scale_lines(lines0_raw + 0.5, s0) - 0.5
1017
+ lines1_raw = scale_lines(lines1_raw + 0.5, s1) - 0.5
1018
+
1019
+ lines0 = torch.from_numpy(lines0.copy())
1020
+ lines1 = torch.from_numpy(lines1.copy())
1021
+ lines0 = scale_lines(lines0 + 0.5, s0) - 0.5
1022
+ lines1 = scale_lines(lines1 + 0.5, s1) - 0.5
1023
+
1024
+ ret = {
1025
+ "image0_orig": image_0,
1026
+ "image1_orig": image_1,
1027
+ "line0": lines0_raw.cpu().numpy(),
1028
+ "line1": lines1_raw.cpu().numpy(),
1029
+ "line0_orig": lines0.cpu().numpy(),
1030
+ "line1_orig": lines1.cpu().numpy(),
1031
+ "line_keypoints0_orig": kpts0_origin,
1032
+ "line_keypoints1_orig": kpts1_origin,
1033
+ }
1034
+ del pred
1035
+ torch.cuda.empty_cache()
1036
+ return ret
1037
+
1038
+
1039
+ @torch.no_grad()
1040
+ def main(
1041
+ conf: Dict,
1042
+ pairs: Path,
1043
+ image_dir: Path,
1044
+ export_dir: Optional[Path] = None,
1045
+ matches: Optional[Path] = None, # out
1046
+ features: Optional[Path] = None, # out
1047
+ features_ref: Optional[Path] = None,
1048
+ max_kps: Optional[int] = 8192,
1049
+ overwrite: bool = False,
1050
+ ) -> Path:
1051
+ logger.info(
1052
+ "Extracting semi-dense features with configuration:"
1053
+ f"\n{pprint.pformat(conf)}"
1054
+ )
1055
+
1056
+ if features is None:
1057
+ features = "feats_"
1058
+
1059
+ if isinstance(features, Path):
1060
+ features_q = features
1061
+ if matches is None:
1062
+ raise ValueError(
1063
+ "Either provide both features and matches as Path"
1064
+ " or both as names."
1065
+ )
1066
+ else:
1067
+ if export_dir is None:
1068
+ raise ValueError(
1069
+ "Provide an export_dir if features and matches"
1070
+ f" are not file paths: {features}, {matches}."
1071
+ )
1072
+ features_q = Path(export_dir, f'{features}{conf["output"]}.h5')
1073
+ if matches is None:
1074
+ matches = Path(export_dir, f'{conf["output"]}_{pairs.stem}.h5')
1075
+
1076
+ if features_ref is None:
1077
+ features_ref = []
1078
+ elif isinstance(features_ref, list):
1079
+ features_ref = list(features_ref)
1080
+ elif isinstance(features_ref, Path):
1081
+ features_ref = [features_ref]
1082
+ else:
1083
+ raise TypeError(str(features_ref))
1084
+
1085
+ match_and_assign(
1086
+ conf,
1087
+ pairs,
1088
+ image_dir,
1089
+ matches,
1090
+ features_q,
1091
+ features_ref,
1092
+ max_kps,
1093
+ overwrite,
1094
+ )
1095
+
1096
+ return features_q, matches
1097
+
1098
+
1099
+ if __name__ == "__main__":
1100
+ parser = argparse.ArgumentParser()
1101
+ parser.add_argument("--pairs", type=Path, required=True)
1102
+ parser.add_argument("--image_dir", type=Path, required=True)
1103
+ parser.add_argument("--export_dir", type=Path, required=True)
1104
+ parser.add_argument(
1105
+ "--matches", type=Path, default=confs["loftr"]["output"]
1106
+ )
1107
+ parser.add_argument(
1108
+ "--features", type=str, default="feats_" + confs["loftr"]["output"]
1109
+ )
1110
+ parser.add_argument(
1111
+ "--conf", type=str, default="loftr", choices=list(confs.keys())
1112
+ )
1113
+ args = parser.parse_args()
1114
+ main(
1115
+ confs[args.conf],
1116
+ args.pairs,
1117
+ args.image_dir,
1118
+ args.export_dir,
1119
+ args.matches,
1120
+ args.features,
1121
+ )
hloc/match_features.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pprint
3
+ from functools import partial
4
+ from pathlib import Path
5
+ from queue import Queue
6
+ from threading import Thread
7
+ from typing import Dict, List, Optional, Tuple, Union
8
+
9
+ import h5py
10
+ import numpy as np
11
+ import torch
12
+ from tqdm import tqdm
13
+
14
+ from . import logger, matchers
15
+ from .utils.base_model import dynamic_load
16
+ from .utils.parsers import names_to_pair, names_to_pair_old, parse_retrieval
17
+
18
+ """
19
+ A set of standard configurations that can be directly selected from the command
20
+ line using their name. Each is a dictionary with the following entries:
21
+ - output: the name of the match file that will be generated.
22
+ - model: the model configuration, as passed to a feature matcher.
23
+ """
24
+ confs = {
25
+ "superglue": {
26
+ "output": "matches-superglue",
27
+ "model": {
28
+ "name": "superglue",
29
+ "weights": "outdoor",
30
+ "sinkhorn_iterations": 50,
31
+ "match_threshold": 0.2,
32
+ },
33
+ "preprocessing": {
34
+ "grayscale": True,
35
+ "resize_max": 1024,
36
+ "dfactor": 8,
37
+ "force_resize": False,
38
+ },
39
+ },
40
+ "superglue-fast": {
41
+ "output": "matches-superglue-it5",
42
+ "model": {
43
+ "name": "superglue",
44
+ "weights": "outdoor",
45
+ "sinkhorn_iterations": 5,
46
+ "match_threshold": 0.2,
47
+ },
48
+ },
49
+ "superpoint-lightglue": {
50
+ "output": "matches-lightglue",
51
+ "model": {
52
+ "name": "lightglue",
53
+ "match_threshold": 0.2,
54
+ "width_confidence": 0.99, # for point pruning
55
+ "depth_confidence": 0.95, # for early stopping,
56
+ "features": "superpoint",
57
+ "model_name": "superpoint_lightglue.pth",
58
+ },
59
+ "preprocessing": {
60
+ "grayscale": True,
61
+ "resize_max": 1024,
62
+ "dfactor": 8,
63
+ "force_resize": False,
64
+ },
65
+ },
66
+ "disk-lightglue": {
67
+ "output": "matches-disk-lightglue",
68
+ "model": {
69
+ "name": "lightglue",
70
+ "match_threshold": 0.2,
71
+ "width_confidence": 0.99, # for point pruning
72
+ "depth_confidence": 0.95, # for early stopping,
73
+ "features": "disk",
74
+ "model_name": "disk_lightglue.pth",
75
+ },
76
+ "preprocessing": {
77
+ "grayscale": True,
78
+ "resize_max": 1024,
79
+ "dfactor": 8,
80
+ "force_resize": False,
81
+ },
82
+ },
83
+ "sift-lightglue": {
84
+ "output": "matches-sift-lightglue",
85
+ "model": {
86
+ "name": "lightglue",
87
+ "match_threshold": 0.2,
88
+ "width_confidence": 0.99, # for point pruning
89
+ "depth_confidence": 0.95, # for early stopping,
90
+ "features": "sift",
91
+ "add_scale_ori": True,
92
+ "model_name": "sift_lightglue.pth",
93
+ },
94
+ "preprocessing": {
95
+ "grayscale": True,
96
+ "resize_max": 1024,
97
+ "dfactor": 8,
98
+ "force_resize": False,
99
+ },
100
+ },
101
+ "sgmnet": {
102
+ "output": "matches-sgmnet",
103
+ "model": {
104
+ "name": "sgmnet",
105
+ "seed_top_k": [256, 256],
106
+ "seed_radius_coe": 0.01,
107
+ "net_channels": 128,
108
+ "layer_num": 9,
109
+ "head": 4,
110
+ "seedlayer": [0, 6],
111
+ "use_mc_seeding": True,
112
+ "use_score_encoding": False,
113
+ "conf_bar": [1.11, 0.1],
114
+ "sink_iter": [10, 100],
115
+ "detach_iter": 1000000,
116
+ "match_threshold": 0.2,
117
+ },
118
+ "preprocessing": {
119
+ "grayscale": True,
120
+ "resize_max": 1024,
121
+ "dfactor": 8,
122
+ "force_resize": False,
123
+ },
124
+ },
125
+ "NN-superpoint": {
126
+ "output": "matches-NN-mutual-dist.7",
127
+ "model": {
128
+ "name": "nearest_neighbor",
129
+ "do_mutual_check": True,
130
+ "distance_threshold": 0.7,
131
+ "match_threshold": 0.2,
132
+ },
133
+ },
134
+ "NN-ratio": {
135
+ "output": "matches-NN-mutual-ratio.8",
136
+ "model": {
137
+ "name": "nearest_neighbor",
138
+ "do_mutual_check": True,
139
+ "ratio_threshold": 0.8,
140
+ "match_threshold": 0.2,
141
+ },
142
+ },
143
+ "NN-mutual": {
144
+ "output": "matches-NN-mutual",
145
+ "model": {
146
+ "name": "nearest_neighbor",
147
+ "do_mutual_check": True,
148
+ "match_threshold": 0.2,
149
+ },
150
+ },
151
+ "Dual-Softmax": {
152
+ "output": "matches-Dual-Softmax",
153
+ "model": {
154
+ "name": "dual_softmax",
155
+ "match_threshold": 0.01,
156
+ "inv_temperature": 20,
157
+ },
158
+ },
159
+ "adalam": {
160
+ "output": "matches-adalam",
161
+ "model": {
162
+ "name": "adalam",
163
+ "match_threshold": 0.2,
164
+ },
165
+ },
166
+ "imp": {
167
+ "output": "matches-imp",
168
+ "model": {
169
+ "name": "imp",
170
+ "match_threshold": 0.2,
171
+ },
172
+ },
173
+ }
174
+
175
+
176
+ class WorkQueue:
177
+ def __init__(self, work_fn, num_threads=1):
178
+ self.queue = Queue(num_threads)
179
+ self.threads = [
180
+ Thread(target=self.thread_fn, args=(work_fn,))
181
+ for _ in range(num_threads)
182
+ ]
183
+ for thread in self.threads:
184
+ thread.start()
185
+
186
+ def join(self):
187
+ for thread in self.threads:
188
+ self.queue.put(None)
189
+ for thread in self.threads:
190
+ thread.join()
191
+
192
+ def thread_fn(self, work_fn):
193
+ item = self.queue.get()
194
+ while item is not None:
195
+ work_fn(item)
196
+ item = self.queue.get()
197
+
198
+ def put(self, data):
199
+ self.queue.put(data)
200
+
201
+
202
+ class FeaturePairsDataset(torch.utils.data.Dataset):
203
+ def __init__(self, pairs, feature_path_q, feature_path_r):
204
+ self.pairs = pairs
205
+ self.feature_path_q = feature_path_q
206
+ self.feature_path_r = feature_path_r
207
+
208
+ def __getitem__(self, idx):
209
+ name0, name1 = self.pairs[idx]
210
+ data = {}
211
+ with h5py.File(self.feature_path_q, "r") as fd:
212
+ grp = fd[name0]
213
+ for k, v in grp.items():
214
+ data[k + "0"] = torch.from_numpy(v.__array__()).float()
215
+ # some matchers might expect an image but only use its size
216
+ data["image0"] = torch.empty((1,) + tuple(grp["image_size"])[::-1])
217
+ with h5py.File(self.feature_path_r, "r") as fd:
218
+ grp = fd[name1]
219
+ for k, v in grp.items():
220
+ data[k + "1"] = torch.from_numpy(v.__array__()).float()
221
+ data["image1"] = torch.empty((1,) + tuple(grp["image_size"])[::-1])
222
+ return data
223
+
224
+ def __len__(self):
225
+ return len(self.pairs)
226
+
227
+
228
+ def writer_fn(inp, match_path):
229
+ pair, pred = inp
230
+ with h5py.File(str(match_path), "a", libver="latest") as fd:
231
+ if pair in fd:
232
+ del fd[pair]
233
+ grp = fd.create_group(pair)
234
+ matches = pred["matches0"][0].cpu().short().numpy()
235
+ grp.create_dataset("matches0", data=matches)
236
+ if "matching_scores0" in pred:
237
+ scores = pred["matching_scores0"][0].cpu().half().numpy()
238
+ grp.create_dataset("matching_scores0", data=scores)
239
+
240
+
241
+ def main(
242
+ conf: Dict,
243
+ pairs: Path,
244
+ features: Union[Path, str],
245
+ export_dir: Optional[Path] = None,
246
+ matches: Optional[Path] = None,
247
+ features_ref: Optional[Path] = None,
248
+ overwrite: bool = False,
249
+ ) -> Path:
250
+ if isinstance(features, Path) or Path(features).exists():
251
+ features_q = features
252
+ if matches is None:
253
+ raise ValueError(
254
+ "Either provide both features and matches as Path"
255
+ " or both as names."
256
+ )
257
+ else:
258
+ if export_dir is None:
259
+ raise ValueError(
260
+ "Provide an export_dir if features is not"
261
+ f" a file path: {features}."
262
+ )
263
+ features_q = Path(export_dir, features + ".h5")
264
+ if matches is None:
265
+ matches = Path(
266
+ export_dir, f'{features}_{conf["output"]}_{pairs.stem}.h5'
267
+ )
268
+
269
+ if features_ref is None:
270
+ features_ref = features_q
271
+ match_from_paths(conf, pairs, matches, features_q, features_ref, overwrite)
272
+
273
+ return matches
274
+
275
+
276
+ def find_unique_new_pairs(pairs_all: List[Tuple[str]], match_path: Path = None):
277
+ """Avoid to recompute duplicates to save time."""
278
+ pairs = set()
279
+ for i, j in pairs_all:
280
+ if (j, i) not in pairs:
281
+ pairs.add((i, j))
282
+ pairs = list(pairs)
283
+ if match_path is not None and match_path.exists():
284
+ with h5py.File(str(match_path), "r", libver="latest") as fd:
285
+ pairs_filtered = []
286
+ for i, j in pairs:
287
+ if (
288
+ names_to_pair(i, j) in fd
289
+ or names_to_pair(j, i) in fd
290
+ or names_to_pair_old(i, j) in fd
291
+ or names_to_pair_old(j, i) in fd
292
+ ):
293
+ continue
294
+ pairs_filtered.append((i, j))
295
+ return pairs_filtered
296
+ return pairs
297
+
298
+
299
+ @torch.no_grad()
300
+ def match_from_paths(
301
+ conf: Dict,
302
+ pairs_path: Path,
303
+ match_path: Path,
304
+ feature_path_q: Path,
305
+ feature_path_ref: Path,
306
+ overwrite: bool = False,
307
+ ) -> Path:
308
+ logger.info(
309
+ "Matching local features with configuration:"
310
+ f"\n{pprint.pformat(conf)}"
311
+ )
312
+
313
+ if not feature_path_q.exists():
314
+ raise FileNotFoundError(f"Query feature file {feature_path_q}.")
315
+ if not feature_path_ref.exists():
316
+ raise FileNotFoundError(f"Reference feature file {feature_path_ref}.")
317
+ match_path.parent.mkdir(exist_ok=True, parents=True)
318
+
319
+ assert pairs_path.exists(), pairs_path
320
+ pairs = parse_retrieval(pairs_path)
321
+ pairs = [(q, r) for q, rs in pairs.items() for r in rs]
322
+ pairs = find_unique_new_pairs(pairs, None if overwrite else match_path)
323
+ if len(pairs) == 0:
324
+ logger.info("Skipping the matching.")
325
+ return
326
+
327
+ device = "cuda" if torch.cuda.is_available() else "cpu"
328
+ Model = dynamic_load(matchers, conf["model"]["name"])
329
+ model = Model(conf["model"]).eval().to(device)
330
+
331
+ dataset = FeaturePairsDataset(pairs, feature_path_q, feature_path_ref)
332
+ loader = torch.utils.data.DataLoader(
333
+ dataset, num_workers=5, batch_size=1, shuffle=False, pin_memory=True
334
+ )
335
+ writer_queue = WorkQueue(partial(writer_fn, match_path=match_path), 5)
336
+
337
+ for idx, data in enumerate(tqdm(loader, smoothing=0.1)):
338
+ data = {
339
+ k: v if k.startswith("image") else v.to(device, non_blocking=True)
340
+ for k, v in data.items()
341
+ }
342
+ pred = model(data)
343
+ pair = names_to_pair(*pairs[idx])
344
+ writer_queue.put((pair, pred))
345
+ writer_queue.join()
346
+ logger.info("Finished exporting matches.")
347
+
348
+
349
+ def scale_keypoints(kpts, scale):
350
+ if np.any(scale != 1.0):
351
+ kpts *= kpts.new_tensor(scale)
352
+ return kpts
353
+
354
+
355
+ @torch.no_grad()
356
+ def match_images(model, feat0, feat1):
357
+ # forward pass to match keypoints
358
+ desc0 = feat0["descriptors"][0]
359
+ desc1 = feat1["descriptors"][0]
360
+ if len(desc0.shape) == 2:
361
+ desc0 = desc0.unsqueeze(0)
362
+ if len(desc1.shape) == 2:
363
+ desc1 = desc1.unsqueeze(0)
364
+ if isinstance(feat0["keypoints"], list):
365
+ feat0["keypoints"] = feat0["keypoints"][0][None]
366
+ if isinstance(feat1["keypoints"], list):
367
+ feat1["keypoints"] = feat1["keypoints"][0][None]
368
+ input_dict = {
369
+ "image0": feat0["image"],
370
+ "keypoints0": feat0["keypoints"],
371
+ "scores0": feat0["scores"][0].unsqueeze(0),
372
+ "descriptors0": desc0,
373
+ "image1": feat1["image"],
374
+ "keypoints1": feat1["keypoints"],
375
+ "scores1": feat1["scores"][0].unsqueeze(0),
376
+ "descriptors1": desc1,
377
+ }
378
+ if "scales" in feat0:
379
+ input_dict = {**input_dict, "scales0": feat0["scales"]}
380
+ if "scales" in feat1:
381
+ input_dict = {**input_dict, "scales1": feat1["scales"]}
382
+ if "oris" in feat0:
383
+ input_dict = {**input_dict, "oris0": feat0["oris"]}
384
+ if "oris" in feat1:
385
+ input_dict = {**input_dict, "oris1": feat1["oris"]}
386
+ pred = model(input_dict)
387
+ pred = {
388
+ k: v.cpu().detach()[0] if isinstance(v, torch.Tensor) else v
389
+ for k, v in pred.items()
390
+ }
391
+ kpts0, kpts1 = (
392
+ feat0["keypoints"][0].cpu().numpy(),
393
+ feat1["keypoints"][0].cpu().numpy(),
394
+ )
395
+ matches, confid = pred["matches0"], pred["matching_scores0"]
396
+ # Keep the matching keypoints.
397
+ valid = matches > -1
398
+ mkpts0 = kpts0[valid]
399
+ mkpts1 = kpts1[matches[valid]]
400
+ mconfid = confid[valid]
401
+ # rescale the keypoints to their original size
402
+ s0 = feat0["original_size"] / feat0["size"]
403
+ s1 = feat1["original_size"] / feat1["size"]
404
+ kpts0_origin = scale_keypoints(torch.from_numpy(kpts0 + 0.5), s0) - 0.5
405
+ kpts1_origin = scale_keypoints(torch.from_numpy(kpts1 + 0.5), s1) - 0.5
406
+
407
+ mkpts0_origin = scale_keypoints(torch.from_numpy(mkpts0 + 0.5), s0) - 0.5
408
+ mkpts1_origin = scale_keypoints(torch.from_numpy(mkpts1 + 0.5), s1) - 0.5
409
+
410
+ ret = {
411
+ "image0_orig": feat0["image_orig"],
412
+ "image1_orig": feat1["image_orig"],
413
+ "keypoints0": kpts0,
414
+ "keypoints1": kpts1,
415
+ "keypoints0_orig": kpts0_origin.numpy(),
416
+ "keypoints1_orig": kpts1_origin.numpy(),
417
+ "mkeypoints0": mkpts0,
418
+ "mkeypoints1": mkpts1,
419
+ "mkeypoints0_orig": mkpts0_origin.numpy(),
420
+ "mkeypoints1_orig": mkpts1_origin.numpy(),
421
+ "mconf": mconfid.numpy(),
422
+ }
423
+ del feat0, feat1, desc0, desc1, kpts0, kpts1, kpts0_origin, kpts1_origin
424
+ torch.cuda.empty_cache()
425
+
426
+ return ret
427
+
428
+
429
+ if __name__ == "__main__":
430
+ parser = argparse.ArgumentParser()
431
+ parser.add_argument("--pairs", type=Path, required=True)
432
+ parser.add_argument("--export_dir", type=Path)
433
+ parser.add_argument(
434
+ "--features", type=str, default="feats-superpoint-n4096-r1024"
435
+ )
436
+ parser.add_argument("--matches", type=Path)
437
+ parser.add_argument(
438
+ "--conf", type=str, default="superglue", choices=list(confs.keys())
439
+ )
440
+ args = parser.parse_args()
441
+ main(confs[args.conf], args.pairs, args.features, args.export_dir)
hloc/matchers/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ def get_matcher(matcher):
2
+ mod = __import__(f"{__name__}.{matcher}", fromlist=[""])
3
+ return getattr(mod, "Model")