lsxi77777 commited on
Commit
a930e1f
·
0 Parent(s):

commit message

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .flake8 +4 -0
  2. .gitattributes +38 -0
  3. .gitignore +28 -0
  4. Dockerfile +27 -0
  5. LICENSE +201 -0
  6. README.md +13 -0
  7. api/__init__.py +42 -0
  8. api/client.py +218 -0
  9. api/config/api.yaml +51 -0
  10. api/server.py +472 -0
  11. api/test/CMakeLists.txt +16 -0
  12. api/test/build_and_run.sh +16 -0
  13. api/test/client.cpp +84 -0
  14. api/test/helper.h +410 -0
  15. app.py +28 -0
  16. assets/demo.gif +3 -0
  17. assets/gui.jpg +3 -0
  18. assets/logo.webp +0 -0
  19. build_docker.sh +3 -0
  20. datasets/.gitignore +0 -0
  21. datasets/show/2/IM_02422.jpg +3 -0
  22. datasets/show/2/IM_05311.jpg +3 -0
  23. datasets/show/3/IM_00748.jpg +3 -0
  24. datasets/show/3/IM_04239.jpg +3 -0
  25. datasets/show/4/IM_00008.jpg +3 -0
  26. datasets/show/4/IM_01534.jpg +3 -0
  27. datasets/show/depth/00022_00194_outdoor_180_010.png +3 -0
  28. datasets/show/depth/00022_00194_outdoor_350_010.png +3 -0
  29. datasets/show/depth/00022_00195_outdoor_000_040.png +3 -0
  30. datasets/show/event/000289.png +3 -0
  31. datasets/show/event/000422.png +3 -0
  32. datasets/show/event/000522.png +3 -0
  33. datasets/show/txt.txt +18 -0
  34. datasets/show/vis/00022_00194_outdoor_180_010.png +3 -0
  35. datasets/show/vis/00022_00194_outdoor_350_010.png +3 -0
  36. datasets/show/vis/00022_00195_outdoor_000_040.png +3 -0
  37. datasets/show/vis/000289.png +3 -0
  38. datasets/show/vis/000422.png +3 -0
  39. datasets/show/vis/000522.png +3 -0
  40. docker/build_docker.bat +3 -0
  41. docker/run_docker.bat +1 -0
  42. docker/run_docker.sh +1 -0
  43. format.sh +3 -0
  44. hloc/__init__.py +66 -0
  45. hloc/__pycache__/__init__.cpython-311.pyc +0 -0
  46. hloc/__pycache__/extract_features.cpython-311.pyc +0 -0
  47. hloc/__pycache__/match_dense.cpython-311.pyc +0 -0
  48. hloc/__pycache__/match_features.cpython-311.pyc +0 -0
  49. hloc/__pycache__/pairs_from_retrieval.cpython-311.pyc +0 -0
  50. hloc/__pycache__/reconstruction.cpython-311.pyc +0 -0
.flake8 ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [flake8]
2
+ max-line-length = 80
3
+ extend-ignore = E203,E501,E402
4
+ exclude = .git,__pycache__,build,.venv/,third_party
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.jpg filter=lfs diff=lfs merge=lfs -text
37
+ *.png filter=lfs diff=lfs merge=lfs -text
38
+ *.gif filter=lfs diff=lfs merge=lfs -text
.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 ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: MINIMA
3
+ emoji: 📈
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.9.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import List
3
+ from pydantic import BaseModel
4
+ import base64
5
+ import io
6
+ import numpy as np
7
+ from fastapi.exceptions import HTTPException
8
+ from PIL import Image
9
+ from pathlib import Path
10
+
11
+ sys.path.append(str(Path(__file__).parents[1]))
12
+ from hloc import logger
13
+
14
+
15
+ class ImagesInput(BaseModel):
16
+ data: List[str] = []
17
+ max_keypoints: List[int] = []
18
+ timestamps: List[str] = []
19
+ grayscale: bool = False
20
+ image_hw: List[List[int]] = [[], []]
21
+ feature_type: int = 0
22
+ rotates: List[float] = []
23
+ scales: List[float] = []
24
+ reference_points: List[List[float]] = []
25
+ binarize: bool = False
26
+
27
+
28
+ def decode_base64_to_image(encoding):
29
+ if encoding.startswith("data:image/"):
30
+ encoding = encoding.split(";")[1].split(",")[1]
31
+ try:
32
+ image = Image.open(io.BytesIO(base64.b64decode(encoding)))
33
+ return image
34
+ except Exception as e:
35
+ logger.warning(f"API cannot decode image: {e}")
36
+ raise HTTPException(
37
+ status_code=500, detail="Invalid encoded image"
38
+ ) from e
39
+
40
+
41
+ def to_base64_nparray(encoding: str) -> np.ndarray:
42
+ return np.array(decode_base64_to_image(encoding)).astype("uint8")
api/client.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:8000"
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
+ Args:
27
+ path (str): The path to the image to read.
28
+ Returns:
29
+ str: The base64 encoded image.
30
+ """
31
+ # Read the image from the file
32
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
33
+
34
+ # Encode the image as a png, NO COMPRESSION!!!
35
+ retval, buffer = cv2.imencode(".png", img)
36
+
37
+ # Encode the JPEG as a base64 string
38
+ b64img = base64.b64encode(buffer).decode("utf-8")
39
+
40
+ return b64img
41
+
42
+
43
+ def do_api_requests(url=API_URL_EXTRACT, **kwargs):
44
+ """
45
+ Helper function to send an API request to the image matching service.
46
+ Args:
47
+ url (str): The URL of the API endpoint to use. Defaults to the
48
+ feature extraction endpoint.
49
+ **kwargs: Additional keyword arguments to pass to the API.
50
+ Returns:
51
+ List[Dict[str, np.ndarray]]: A list of dictionaries containing the
52
+ extracted features. The keys are "keypoints", "descriptors", and
53
+ "scores", and the values are ndarrays of shape (N, 2), (N, ?),
54
+ and (N,), respectively.
55
+ """
56
+ # Set up the request body
57
+ reqbody = {
58
+ # List of image data base64 encoded
59
+ "data": [],
60
+ # List of maximum number of keypoints to extract from each image
61
+ "max_keypoints": [100, 100],
62
+ # List of timestamps for each image (not used?)
63
+ "timestamps": ["0", "1"],
64
+ # Whether to convert the images to grayscale
65
+ "grayscale": 0,
66
+ # List of image height and width
67
+ "image_hw": [[640, 480], [320, 240]],
68
+ # Type of feature to extract
69
+ "feature_type": 0,
70
+ # List of rotation angles for each image
71
+ "rotates": [0.0, 0.0],
72
+ # List of scale factors for each image
73
+ "scales": [1.0, 1.0],
74
+ # List of reference points for each image (not used)
75
+ "reference_points": [[640, 480], [320, 240]],
76
+ # Whether to binarize the descriptors
77
+ "binarize": True,
78
+ }
79
+ # Update the request body with the additional keyword arguments
80
+ reqbody.update(kwargs)
81
+ try:
82
+ # Send the request
83
+ r = requests.post(url, json=reqbody)
84
+ if r.status_code == 200:
85
+ # Return the response
86
+ return r.json()
87
+ else:
88
+ # Print an error message if the response code is not 200
89
+ print(f"Error: Response code {r.status_code} - {r.text}")
90
+ except Exception as e:
91
+ # Print an error message if an exception occurs
92
+ print(f"An error occurred: {e}")
93
+
94
+
95
+ def send_request_match(path0: str, path1: str) -> Dict[str, np.ndarray]:
96
+ """
97
+ Send a request to the API to generate a match between two images.
98
+ Args:
99
+ path0 (str): The path to the first image.
100
+ path1 (str): The path to the second image.
101
+ Returns:
102
+ Dict[str, np.ndarray]: A dictionary containing the generated matches.
103
+ The keys are "keypoints0", "keypoints1", "matches0", and "matches1",
104
+ and the values are ndarrays of shape (N, 2), (N, 2), (N, 2), and
105
+ (N, 2), respectively.
106
+ """
107
+ files = {"image0": open(path0, "rb"), "image1": open(path1, "rb")}
108
+ try:
109
+ # TODO: replace files with post json
110
+ response = requests.post(API_URL_MATCH, files=files)
111
+ pred = {}
112
+ if response.status_code == 200:
113
+ pred = response.json()
114
+ for key in list(pred.keys()):
115
+ pred[key] = np.array(pred[key])
116
+ else:
117
+ print(
118
+ f"Error: Response code {response.status_code} - {response.text}"
119
+ )
120
+ finally:
121
+ files["image0"].close()
122
+ files["image1"].close()
123
+ return pred
124
+
125
+
126
+ def send_request_extract(
127
+ input_images: str, viz: bool = False
128
+ ) -> List[Dict[str, np.ndarray]]:
129
+ """
130
+ Send a request to the API to extract features from an image.
131
+ Args:
132
+ input_images (str): The path to the image.
133
+ Returns:
134
+ List[Dict[str, np.ndarray]]: A list of dictionaries containing the
135
+ extracted features. The keys are "keypoints", "descriptors", and
136
+ "scores", and the values are ndarrays of shape (N, 2), (N, 128),
137
+ and (N,), respectively.
138
+ """
139
+ image_data = read_image(input_images)
140
+ inputs = {
141
+ "data": [image_data],
142
+ }
143
+ response = do_api_requests(
144
+ url=API_URL_EXTRACT,
145
+ **inputs,
146
+ )
147
+ # breakpoint()
148
+ # print("Keypoints detected: {}".format(len(response[0]["keypoints"])))
149
+
150
+ # draw matching, debug only
151
+ if viz:
152
+ from hloc.utils.viz import plot_keypoints
153
+ from ui.viz import fig2im, plot_images
154
+
155
+ kpts = np.array(response[0]["keypoints_orig"])
156
+ if "image_orig" in response[0].keys():
157
+ img_orig = np.array(["image_orig"])
158
+
159
+ output_keypoints = plot_images([img_orig], titles="titles", dpi=300)
160
+ plot_keypoints([kpts])
161
+ output_keypoints = fig2im(output_keypoints)
162
+ cv2.imwrite(
163
+ "demo_match.jpg",
164
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
165
+ )
166
+ return response
167
+
168
+
169
+ def get_api_version():
170
+ try:
171
+ response = requests.get(API_VERSION).json()
172
+ print("API VERSION: {}".format(response["version"]))
173
+ except Exception as e:
174
+ print(f"An error occurred: {e}")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ parser = argparse.ArgumentParser(
179
+ description="Send text to stable audio server and receive generated audio."
180
+ )
181
+ parser.add_argument(
182
+ "--image0",
183
+ required=False,
184
+ help="Path for the file's melody",
185
+ default="datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot45.jpg",
186
+ )
187
+ parser.add_argument(
188
+ "--image1",
189
+ required=False,
190
+ help="Path for the file's melody",
191
+ default="datasets/sacre_coeur/mapping_rot/02928139_3448003521_rot90.jpg",
192
+ )
193
+ args = parser.parse_args()
194
+
195
+ # get api version
196
+ get_api_version()
197
+
198
+ # request match
199
+ # for i in range(10):
200
+ # t1 = time.time()
201
+ # preds = send_request_match(args.image0, args.image1)
202
+ # t2 = time.time()
203
+ # print(
204
+ # "Time cost1: {} seconds, matched: {}".format(
205
+ # (t2 - t1), len(preds["mmkeypoints0_orig"])
206
+ # )
207
+ # )
208
+
209
+ # request extract
210
+ for i in range(1000):
211
+ t1 = time.time()
212
+ preds = send_request_extract(args.image0)
213
+ t2 = time.time()
214
+ print(f"Time cost2: {(t2 - t1)} seconds")
215
+
216
+ # dump preds
217
+ with open("preds.pkl", "wb") as f:
218
+ pickle.dump(preds, f)
api/config/api.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file was generated using the `serve build` command on Ray v2.38.0.
2
+
3
+ proxy_location: EveryNode
4
+ http_options:
5
+ host: 0.0.0.0
6
+ port: 8000
7
+
8
+ grpc_options:
9
+ port: 9000
10
+ grpc_servicer_functions: []
11
+
12
+ logging_config:
13
+ encoding: TEXT
14
+ log_level: INFO
15
+ logs_dir: null
16
+ enable_access_log: true
17
+
18
+ applications:
19
+ - name: app1
20
+ route_prefix: /
21
+ import_path: api.server:service
22
+ runtime_env: {}
23
+ deployments:
24
+ - name: ImageMatchingService
25
+ num_replicas: 4
26
+ ray_actor_options:
27
+ num_cpus: 2.0
28
+ num_gpus: 1.0
29
+
30
+ api:
31
+ feature:
32
+ output: feats-superpoint-n4096-rmax1600
33
+ model:
34
+ name: superpoint
35
+ nms_radius: 3
36
+ max_keypoints: 4096
37
+ keypoint_threshold: 0.005
38
+ preprocessing:
39
+ grayscale: True
40
+ force_resize: True
41
+ resize_max: 1600
42
+ width: 640
43
+ height: 480
44
+ dfactor: 8
45
+ matcher:
46
+ output: matches-NN-mutual
47
+ model:
48
+ name: nearest_neighbor
49
+ do_mutual_check: True
50
+ match_threshold: 0.2
51
+ dense: False
api/server.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # server.py
2
+ import warnings
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Optional, Union
5
+ import yaml
6
+
7
+ import ray
8
+ from ray import serve
9
+
10
+ import cv2
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import torch
14
+ from fastapi import FastAPI, File, UploadFile
15
+ from fastapi.responses import JSONResponse
16
+ from PIL import Image
17
+
18
+ from api import ImagesInput, to_base64_nparray
19
+ from hloc import DEVICE, extract_features, logger, match_dense, match_features
20
+ from hloc.utils.viz import add_text, plot_keypoints
21
+ from ui import get_version
22
+ from ui.utils import filter_matches, get_feature_model, get_model
23
+ from ui.viz import display_matches, fig2im, plot_images
24
+
25
+ warnings.simplefilter("ignore")
26
+ app = FastAPI()
27
+ if ray.is_initialized():
28
+ ray.shutdown()
29
+ ray.init(
30
+ dashboard_port=8265,
31
+ ignore_reinit_error=True,
32
+ )
33
+ serve.start(
34
+ http_options={"host": "0.0.0.0", "port": 8000},
35
+ )
36
+
37
+
38
+ class ImageMatchingAPI(torch.nn.Module):
39
+ default_conf = {
40
+ "ransac": {
41
+ "enable": True,
42
+ "estimator": "poselib",
43
+ "geometry": "Fundamental",
44
+ "method": "RANSAC",
45
+ "reproj_threshold": 8,
46
+ "confidence": 0.99999,
47
+ "max_iter": 2000,
48
+ },
49
+ }
50
+
51
+ def __init__(
52
+ self,
53
+ conf: dict = {},
54
+ device: str = "cpu",
55
+ detect_threshold: float = 0.015,
56
+ max_keypoints: int = 1024,
57
+ match_threshold: float = 0.2,
58
+ ) -> None:
59
+ """
60
+ Initializes an instance of the ImageMatchingAPI class.
61
+ Args:
62
+ conf (dict): A dictionary containing the configuration parameters.
63
+ device (str, optional): The device to use for computation. Defaults to "cpu".
64
+ detect_threshold (float, optional): The threshold for detecting keypoints. Defaults to 0.015.
65
+ max_keypoints (int, optional): The maximum number of keypoints to extract. Defaults to 1024.
66
+ match_threshold (float, optional): The threshold for matching keypoints. Defaults to 0.2.
67
+ Returns:
68
+ None
69
+ """
70
+ super().__init__()
71
+ self.device = device
72
+ self.conf = {**self.default_conf, **conf}
73
+ self._updata_config(detect_threshold, max_keypoints, match_threshold)
74
+ self._init_models()
75
+ if device == "cuda":
76
+ memory_allocated = torch.cuda.memory_allocated(device)
77
+ memory_reserved = torch.cuda.memory_reserved(device)
78
+ logger.info(
79
+ f"GPU memory allocated: {memory_allocated / 1024**2:.3f} MB"
80
+ )
81
+ logger.info(
82
+ f"GPU memory reserved: {memory_reserved / 1024**2:.3f} MB"
83
+ )
84
+ self.pred = None
85
+
86
+ def parse_match_config(self, conf):
87
+ if conf["dense"]:
88
+ return {
89
+ **conf,
90
+ "matcher": match_dense.confs.get(
91
+ conf["matcher"]["model"]["name"]
92
+ ),
93
+ "dense": True,
94
+ }
95
+ else:
96
+ return {
97
+ **conf,
98
+ "feature": extract_features.confs.get(
99
+ conf["feature"]["model"]["name"]
100
+ ),
101
+ "matcher": match_features.confs.get(
102
+ conf["matcher"]["model"]["name"]
103
+ ),
104
+ "dense": False,
105
+ }
106
+
107
+ def _updata_config(
108
+ self,
109
+ detect_threshold: float = 0.015,
110
+ max_keypoints: int = 1024,
111
+ match_threshold: float = 0.2,
112
+ ):
113
+ self.dense = self.conf["dense"]
114
+ if self.conf["dense"]:
115
+ try:
116
+ self.conf["matcher"]["model"][
117
+ "match_threshold"
118
+ ] = match_threshold
119
+ except TypeError as e:
120
+ logger.error(e)
121
+ else:
122
+ self.conf["feature"]["model"]["max_keypoints"] = max_keypoints
123
+ self.conf["feature"]["model"][
124
+ "keypoint_threshold"
125
+ ] = detect_threshold
126
+ self.extract_conf = self.conf["feature"]
127
+
128
+ self.match_conf = self.conf["matcher"]
129
+
130
+ def _init_models(self):
131
+ # initialize matcher
132
+ self.matcher = get_model(self.match_conf)
133
+ # initialize extractor
134
+ if self.dense:
135
+ self.extractor = None
136
+ else:
137
+ self.extractor = get_feature_model(self.conf["feature"])
138
+
139
+ def _forward(self, img0, img1):
140
+ if self.dense:
141
+ pred = match_dense.match_images(
142
+ self.matcher,
143
+ img0,
144
+ img1,
145
+ self.match_conf["preprocessing"],
146
+ device=self.device,
147
+ )
148
+ last_fixed = "{}".format( # noqa: F841
149
+ self.match_conf["model"]["name"]
150
+ )
151
+ else:
152
+ pred0 = extract_features.extract(
153
+ self.extractor, img0, self.extract_conf["preprocessing"]
154
+ )
155
+ pred1 = extract_features.extract(
156
+ self.extractor, img1, self.extract_conf["preprocessing"]
157
+ )
158
+ pred = match_features.match_images(self.matcher, pred0, pred1)
159
+ return pred
160
+
161
+ def _convert_pred(self, pred):
162
+ ret = {
163
+ k: v.cpu().detach()[0].numpy() if isinstance(v, torch.Tensor) else v
164
+ for k, v in pred.items()
165
+ }
166
+ ret = {
167
+ k: v[0].cpu().detach().numpy() if isinstance(v, list) else v
168
+ for k, v in ret.items()
169
+ }
170
+ return ret
171
+
172
+ @torch.inference_mode()
173
+ def extract(self, img0: np.ndarray, **kwargs) -> Dict[str, np.ndarray]:
174
+ """Extract features from a single image.
175
+ Args:
176
+ img0 (np.ndarray): image
177
+ Returns:
178
+ Dict[str, np.ndarray]: feature dict
179
+ """
180
+
181
+ # setting prams
182
+ self.extractor.conf["max_keypoints"] = kwargs.get("max_keypoints", 512)
183
+ self.extractor.conf["keypoint_threshold"] = kwargs.get(
184
+ "keypoint_threshold", 0.0
185
+ )
186
+
187
+ pred = extract_features.extract(
188
+ self.extractor, img0, self.extract_conf["preprocessing"]
189
+ )
190
+ pred = self._convert_pred(pred)
191
+ # back to origin scale
192
+ s0 = pred["original_size"] / pred["size"]
193
+ pred["keypoints_orig"] = (
194
+ match_features.scale_keypoints(pred["keypoints"] + 0.5, s0) - 0.5
195
+ )
196
+ # TODO: rotate back
197
+ binarize = kwargs.get("binarize", False)
198
+ if binarize:
199
+ assert "descriptors" in pred
200
+ pred["descriptors"] = (pred["descriptors"] > 0).astype(np.uint8)
201
+ pred["descriptors"] = pred["descriptors"].T # N x DIM
202
+ return pred
203
+
204
+ @torch.inference_mode()
205
+ def forward(
206
+ self,
207
+ img0: np.ndarray,
208
+ img1: np.ndarray,
209
+ ) -> Dict[str, np.ndarray]:
210
+ """
211
+ Forward pass of the image matching API.
212
+ Args:
213
+ img0: A 3D NumPy array of shape (H, W, C) representing the first image.
214
+ Values are in the range [0, 1] and are in RGB mode.
215
+ img1: A 3D NumPy array of shape (H, W, C) representing the second image.
216
+ Values are in the range [0, 1] and are in RGB mode.
217
+ Returns:
218
+ A dictionary containing the following keys:
219
+ - image0_orig: The original image 0.
220
+ - image1_orig: The original image 1.
221
+ - keypoints0_orig: The keypoints detected in image 0.
222
+ - keypoints1_orig: The keypoints detected in image 1.
223
+ - mkeypoints0_orig: The raw matches between image 0 and image 1.
224
+ - mkeypoints1_orig: The raw matches between image 1 and image 0.
225
+ - mmkeypoints0_orig: The RANSAC inliers in image 0.
226
+ - mmkeypoints1_orig: The RANSAC inliers in image 1.
227
+ - mconf: The confidence scores for the raw matches.
228
+ - mmconf: The confidence scores for the RANSAC inliers.
229
+ """
230
+ # Take as input a pair of images (not a batch)
231
+ assert isinstance(img0, np.ndarray)
232
+ assert isinstance(img1, np.ndarray)
233
+ self.pred = self._forward(img0, img1)
234
+ if self.conf["ransac"]["enable"]:
235
+ self.pred = self._geometry_check(self.pred)
236
+ return self.pred
237
+
238
+ def _geometry_check(
239
+ self,
240
+ pred: Dict[str, Any],
241
+ ) -> Dict[str, Any]:
242
+ """
243
+ Filter matches using RANSAC. If keypoints are available, filter by keypoints.
244
+ If lines are available, filter by lines. If both keypoints and lines are
245
+ available, filter by keypoints.
246
+ Args:
247
+ pred (Dict[str, Any]): dict of matches, including original keypoints.
248
+ See :func:`filter_matches` for the expected keys.
249
+ Returns:
250
+ Dict[str, Any]: filtered matches
251
+ """
252
+ pred = filter_matches(
253
+ pred,
254
+ ransac_method=self.conf["ransac"]["method"],
255
+ ransac_reproj_threshold=self.conf["ransac"]["reproj_threshold"],
256
+ ransac_confidence=self.conf["ransac"]["confidence"],
257
+ ransac_max_iter=self.conf["ransac"]["max_iter"],
258
+ )
259
+ return pred
260
+
261
+ def visualize(
262
+ self,
263
+ log_path: Optional[Path] = None,
264
+ ) -> None:
265
+ """
266
+ Visualize the matches.
267
+ Args:
268
+ log_path (Path, optional): The directory to save the images. Defaults to None.
269
+ Returns:
270
+ None
271
+ """
272
+ if self.conf["dense"]:
273
+ postfix = str(self.conf["matcher"]["model"]["name"])
274
+ else:
275
+ postfix = "{}_{}".format(
276
+ str(self.conf["feature"]["model"]["name"]),
277
+ str(self.conf["matcher"]["model"]["name"]),
278
+ )
279
+ titles = [
280
+ "Image 0 - Keypoints",
281
+ "Image 1 - Keypoints",
282
+ ]
283
+ pred: Dict[str, Any] = self.pred
284
+ image0: np.ndarray = pred["image0_orig"]
285
+ image1: np.ndarray = pred["image1_orig"]
286
+ output_keypoints: np.ndarray = plot_images(
287
+ [image0, image1], titles=titles, dpi=300
288
+ )
289
+ if (
290
+ "keypoints0_orig" in pred.keys()
291
+ and "keypoints1_orig" in pred.keys()
292
+ ):
293
+ plot_keypoints([pred["keypoints0_orig"], pred["keypoints1_orig"]])
294
+ text: str = (
295
+ f"# keypoints0: {len(pred['keypoints0_orig'])} \n"
296
+ + f"# keypoints1: {len(pred['keypoints1_orig'])}"
297
+ )
298
+ add_text(0, text, fs=15)
299
+ output_keypoints = fig2im(output_keypoints)
300
+ # plot images with raw matches
301
+ titles = [
302
+ "Image 0 - Raw matched keypoints",
303
+ "Image 1 - Raw matched keypoints",
304
+ ]
305
+ output_matches_raw, num_matches_raw = display_matches(
306
+ pred, titles=titles, tag="KPTS_RAW"
307
+ )
308
+ # plot images with ransac matches
309
+ titles = [
310
+ "Image 0 - Ransac matched keypoints",
311
+ "Image 1 - Ransac matched keypoints",
312
+ ]
313
+ output_matches_ransac, num_matches_ransac = display_matches(
314
+ pred, titles=titles, tag="KPTS_RANSAC"
315
+ )
316
+ if log_path is not None:
317
+ img_keypoints_path: Path = log_path / f"img_keypoints_{postfix}.png"
318
+ img_matches_raw_path: Path = (
319
+ log_path / f"img_matches_raw_{postfix}.png"
320
+ )
321
+ img_matches_ransac_path: Path = (
322
+ log_path / f"img_matches_ransac_{postfix}.png"
323
+ )
324
+ cv2.imwrite(
325
+ str(img_keypoints_path),
326
+ output_keypoints[:, :, ::-1].copy(), # RGB -> BGR
327
+ )
328
+ cv2.imwrite(
329
+ str(img_matches_raw_path),
330
+ output_matches_raw[:, :, ::-1].copy(), # RGB -> BGR
331
+ )
332
+ cv2.imwrite(
333
+ str(img_matches_ransac_path),
334
+ output_matches_ransac[:, :, ::-1].copy(), # RGB -> BGR
335
+ )
336
+ plt.close("all")
337
+
338
+
339
+ @serve.deployment(
340
+ num_replicas=4,
341
+ ray_actor_options={"num_cpus": 2, "num_gpus": 1}
342
+ )
343
+ @serve.ingress(app)
344
+ class ImageMatchingService:
345
+ def __init__(self, conf: dict, device: str):
346
+ self.conf = conf
347
+ self.api = ImageMatchingAPI(conf=conf, device=device)
348
+
349
+ @app.get("/")
350
+ def root(self):
351
+ return "Hello, world!"
352
+
353
+ @app.get("/version")
354
+ async def version(self):
355
+ return {"version": get_version()}
356
+
357
+ @app.post("/v1/match")
358
+ async def match(
359
+ self, image0: UploadFile = File(...), image1: UploadFile = File(...)
360
+ ):
361
+ """
362
+ Handle the image matching request and return the processed result.
363
+ Args:
364
+ image0 (UploadFile): The first image file for matching.
365
+ image1 (UploadFile): The second image file for matching.
366
+ Returns:
367
+ JSONResponse: A JSON response containing the filtered match results
368
+ or an error message in case of failure.
369
+ """
370
+ try:
371
+ # Load the images from the uploaded files
372
+ image0_array = self.load_image(image0)
373
+ image1_array = self.load_image(image1)
374
+ print('image0_array',image0_array.shape)
375
+ print('image1_array',image1_array.shape)
376
+
377
+ # Perform image matching using the API
378
+ output = self.api(image0_array, image1_array)
379
+
380
+ # Keys to skip in the output
381
+ skip_keys = ["image0_orig", "image1_orig"]
382
+
383
+ # Postprocess the output to filter unwanted data
384
+ pred = self.postprocess(output, skip_keys)
385
+
386
+ # Return the filtered prediction as a JSON response
387
+ return JSONResponse(content=pred)
388
+ except Exception as e:
389
+ # Return an error message with status code 500 in case of exception
390
+ return JSONResponse(content={"error": str(e)}, status_code=500)
391
+
392
+ @app.post("/v1/extract")
393
+ async def extract(self, input_info: ImagesInput):
394
+ """
395
+ Extract keypoints and descriptors from images.
396
+ Args:
397
+ input_info: An object containing the image data and options.
398
+ Returns:
399
+ A list of dictionaries containing the keypoints and descriptors.
400
+ """
401
+ try:
402
+ preds = []
403
+ for i, input_image in enumerate(input_info.data):
404
+ # Load the image from the input data
405
+ image_array = to_base64_nparray(input_image)
406
+ # Extract keypoints and descriptors
407
+ output = self.api.extract(
408
+ image_array,
409
+ max_keypoints=input_info.max_keypoints[i],
410
+ binarize=input_info.binarize,
411
+ )
412
+ # Do not return the original image and image_orig
413
+ # skip_keys = ["image", "image_orig"]
414
+ skip_keys = []
415
+
416
+ # Postprocess the output
417
+ pred = self.postprocess(output, skip_keys)
418
+ preds.append(pred)
419
+ # Return the list of extracted features
420
+ return JSONResponse(content=preds)
421
+ except Exception as e:
422
+ # Return an error message if an exception occurs
423
+ return JSONResponse(content={"error": str(e)}, status_code=500)
424
+
425
+ def load_image(self, file_path: Union[str, UploadFile]) -> np.ndarray:
426
+ """
427
+ Reads an image from a file path or an UploadFile object.
428
+ Args:
429
+ file_path: A file path or an UploadFile object.
430
+ Returns:
431
+ A numpy array representing the image.
432
+ """
433
+ if isinstance(file_path, str):
434
+ file_path = Path(file_path).resolve(strict=False)
435
+ else:
436
+ file_path = file_path.file
437
+ with Image.open(file_path) as img:
438
+ image_array = np.array(img)
439
+ return image_array
440
+
441
+ def postprocess(
442
+ self, output: dict, skip_keys: list, binarize: bool = True
443
+ ) -> dict:
444
+ pred = {}
445
+ for key, value in output.items():
446
+ if key in skip_keys:
447
+ continue
448
+ if isinstance(value, np.ndarray):
449
+ pred[key] = value.tolist()
450
+ return pred
451
+
452
+ def run(self, host: str = "0.0.0.0", port: int = 8001):
453
+ import uvicorn
454
+ uvicorn.run(app, host=host, port=port)
455
+
456
+
457
+ def read_config(config_path: Path) -> dict:
458
+ with open(config_path, "r") as f:
459
+ conf = yaml.safe_load(f)
460
+ return conf
461
+
462
+
463
+ # api server
464
+ conf = read_config(Path(__file__).parent / "config/api.yaml")
465
+ service = ImageMatchingService.bind(conf=conf["api"], device=DEVICE)
466
+
467
+ # handle = serve.run(service, route_prefix="/")
468
+ # serve run api.server_ray:service
469
+
470
+ # build to generate config file
471
+ # serve build api.server_ray:service -o api/config/ray.yaml
472
+ # serve run api/config/ray.yaml
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
+ }
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()
assets/demo.gif ADDED

Git LFS Details

  • SHA256: 3f163c0e2699181897c81c68e01c60fa4289e886a2a40932d53dd529262d3735
  • Pointer size: 132 Bytes
  • Size of remote file: 8.91 MB
assets/gui.jpg ADDED

Git LFS Details

  • SHA256: a783162639d05631f34e8e3e9a7df682197a76f675265ebbaa639927e08473f7
  • Pointer size: 132 Bytes
  • Size of remote file: 1.67 MB
assets/logo.webp ADDED
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
datasets/.gitignore ADDED
File without changes
datasets/show/2/IM_02422.jpg ADDED

Git LFS Details

  • SHA256: 2a0ed0d6d30cf805ca925d760af5993b089dfc558b6591c49cb4b54498760ee9
  • Pointer size: 130 Bytes
  • Size of remote file: 96.2 kB
datasets/show/2/IM_05311.jpg ADDED

Git LFS Details

  • SHA256: 96a49ba23aa74f975bf450fde7430fc46ae3651e6a684d949243fe885c351c41
  • Pointer size: 131 Bytes
  • Size of remote file: 240 kB
datasets/show/3/IM_00748.jpg ADDED

Git LFS Details

  • SHA256: c84d1306188e084ba63e0e215f090fb6dae20caa5359b62a3c57d8bf7b0df384
  • Pointer size: 130 Bytes
  • Size of remote file: 35.5 kB
datasets/show/3/IM_04239.jpg ADDED

Git LFS Details

  • SHA256: abc4f9403bb5c0952a5cc56b7ed4ef70a8042b1dcde40dea92a9e130a2adc9f3
  • Pointer size: 130 Bytes
  • Size of remote file: 84.1 kB
datasets/show/4/IM_00008.jpg ADDED

Git LFS Details

  • SHA256: 22b468bada59aad1ce940e94c899577293d3d4141f19bd84dfac4ec9bfe57a54
  • Pointer size: 130 Bytes
  • Size of remote file: 62.8 kB
datasets/show/4/IM_01534.jpg ADDED

Git LFS Details

  • SHA256: fdb044abe4a20d637934ab84716cfcdf1c7fed3fa0cc6f7a6f04e6ac4f450f36
  • Pointer size: 131 Bytes
  • Size of remote file: 142 kB
datasets/show/depth/00022_00194_outdoor_180_010.png ADDED

Git LFS Details

  • SHA256: 62e46e699b992bbbae6c1637be29e5deb1c72010b085048020a76f21aae74b54
  • Pointer size: 131 Bytes
  • Size of remote file: 541 kB
datasets/show/depth/00022_00194_outdoor_350_010.png ADDED

Git LFS Details

  • SHA256: d79ad3a482b78594693a2cc844bb558818f547d11ecc63836093745f332f4171
  • Pointer size: 131 Bytes
  • Size of remote file: 556 kB
datasets/show/depth/00022_00195_outdoor_000_040.png ADDED

Git LFS Details

  • SHA256: d38b43b56e8401b4de8b4b1154ca54e82558fe00dfb9695794e07ec5a0400035
  • Pointer size: 130 Bytes
  • Size of remote file: 69.7 kB
datasets/show/event/000289.png ADDED

Git LFS Details

  • SHA256: 8cc4816bdf05ea9c762f2636338ad142c547a7749c698a92dbeaff6a108e43f5
  • Pointer size: 131 Bytes
  • Size of remote file: 112 kB
datasets/show/event/000422.png ADDED

Git LFS Details

  • SHA256: eb262e093b07c5935a689641551a3f6e6850b706b59121fa800ce994ffb78634
  • Pointer size: 131 Bytes
  • Size of remote file: 117 kB
datasets/show/event/000522.png ADDED

Git LFS Details

  • SHA256: ff88e7bbbdfdb57f1cfd09da9ca9a014d4e7e510702edb3d0d968fb1b77a1b7d
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
datasets/show/txt.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2/IM_05311.jpg
2
+ 2/IM_02422.jpg
3
+ 3/IM_00748.jpg
4
+ 3/IM_04239.jpg
5
+ 4/IM_00008.jpg
6
+ 4/IM_01534.jpg
7
+ vis/00022_00194_outdoor_180_010.png
8
+ depth/00022_00194_outdoor_180_010.png
9
+ vis/00022_00194_outdoor_350_010.png
10
+ depth/00022_00194_outdoor_350_010.png
11
+ vis/00022_00195_outdoor_000_040.png
12
+ depth/00022_00195_outdoor_000_040.png
13
+ vis/000289.png
14
+ event/000289.png
15
+ vis/000422.png
16
+ event/000422.png
17
+ vis/000522.png
18
+ event/000522.png
datasets/show/vis/00022_00194_outdoor_180_010.png ADDED

Git LFS Details

  • SHA256: a778c06a04ae8be8bdbc8ca720de1d33858f9dbfb5a22a1cbe9e34ed04fece5b
  • Pointer size: 131 Bytes
  • Size of remote file: 605 kB
datasets/show/vis/00022_00194_outdoor_350_010.png ADDED

Git LFS Details

  • SHA256: b6db6390532b0d9fe705d59742956aa9c5330c678774d46d4245c91adb34fdac
  • Pointer size: 131 Bytes
  • Size of remote file: 659 kB
datasets/show/vis/00022_00195_outdoor_000_040.png ADDED

Git LFS Details

  • SHA256: 809e2e5aaf6674a65e55504f6a6a3c63dd77b6fdf6e964ee69a0b1a7020e2713
  • Pointer size: 131 Bytes
  • Size of remote file: 541 kB
datasets/show/vis/000289.png ADDED

Git LFS Details

  • SHA256: b2a38af4917e0f0f7b220f63db81e1de53021241fb34c813d25ee9a7c0b93f3e
  • Pointer size: 131 Bytes
  • Size of remote file: 461 kB
datasets/show/vis/000422.png ADDED

Git LFS Details

  • SHA256: 8ea390ff9baeb0c3824d36d2cb3df7181fd6d4d67c88b865aa1155bb4ed0e43d
  • Pointer size: 131 Bytes
  • Size of remote file: 422 kB
datasets/show/vis/000522.png ADDED

Git LFS Details

  • SHA256: 2fc14275ac9cd6f5cbdad0a7cc3bfd00606ddd6eccc33fb0f1296912855160c5
  • Pointer size: 131 Bytes
  • Size of remote file: 415 kB
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,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+
4
+ import torch
5
+ from packaging import version
6
+
7
+ __version__ = "1.5"
8
+
9
+ LOG_PATH = "log.txt"
10
+
11
+
12
+ def read_logs():
13
+ sys.stdout.flush()
14
+ with open(LOG_PATH, "r") as f:
15
+ return f.read()
16
+
17
+
18
+ def flush_logs():
19
+ sys.stdout.flush()
20
+ logs = open(LOG_PATH, "w")
21
+ logs.close()
22
+
23
+
24
+ formatter = logging.Formatter(
25
+ fmt="[%(asctime)s %(name)s %(levelname)s] %(message)s",
26
+ datefmt="%Y/%m/%d %H:%M:%S",
27
+ )
28
+
29
+ logs_file = open(LOG_PATH, "w")
30
+ logs_file.close()
31
+
32
+ file_handler = logging.FileHandler(filename=LOG_PATH)
33
+ file_handler.setFormatter(formatter)
34
+ file_handler.setLevel(logging.INFO)
35
+ stdout_handler = logging.StreamHandler()
36
+ stdout_handler.setFormatter(formatter)
37
+ stdout_handler.setLevel(logging.INFO)
38
+ logger = logging.getLogger("hloc")
39
+ logger.setLevel(logging.INFO)
40
+ logger.addHandler(file_handler)
41
+ logger.addHandler(stdout_handler)
42
+ logger.propagate = False
43
+
44
+ try:
45
+ import pycolmap
46
+ except ImportError:
47
+ logger.warning("pycolmap is not installed, some features may not work.")
48
+ else:
49
+ min_version = version.parse("0.6.0")
50
+ found_version = pycolmap.__version__
51
+ if found_version != "dev":
52
+ version = version.parse(found_version)
53
+ if version < min_version:
54
+ s = f"pycolmap>={min_version}"
55
+ logger.warning(
56
+ "hloc requires %s but found pycolmap==%s, "
57
+ 'please upgrade with `pip install --upgrade "%s"`',
58
+ s,
59
+ found_version,
60
+ s,
61
+ )
62
+
63
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
64
+
65
+ # model hub: https://huggingface.co/Realcat/imatchui_checkpoint
66
+ MODEL_REPO_ID = "Realcat/imatchui_checkpoints"
hloc/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (3.19 kB). View file
 
hloc/__pycache__/extract_features.cpython-311.pyc ADDED
Binary file (20.6 kB). View file
 
hloc/__pycache__/match_dense.cpython-311.pyc ADDED
Binary file (49.5 kB). View file
 
hloc/__pycache__/match_features.cpython-311.pyc ADDED
Binary file (20.8 kB). View file
 
hloc/__pycache__/pairs_from_retrieval.cpython-311.pyc ADDED
Binary file (9.51 kB). View file
 
hloc/__pycache__/reconstruction.cpython-311.pyc ADDED
Binary file (9.89 kB). View file