-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolmap_model.py
More file actions
421 lines (351 loc) · 15.4 KB
/
colmap_model.py
File metadata and controls
421 lines (351 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import numpy as np
from pathlib import Path
from typing import Tuple, Dict, List
from colmap.read_write_model import *
class ColmapModelReader:
"""
Import SFM model data from COLMAP database (ground truth):
- get image id -> pose, intrinsics
- write intrinsics & poses to text file (as queries for MeshLoc pipeline)
"""
def __init__(self, path_to_data: Path):
self.path_to_data = path_to_data
self.cameras, self.images, self.points3d = read_model(path_to_data)
"""
- images[image_id] = Image(id, qvec, tvec, camera_id, name, xys, point3D_ids)
- cameras[camera_id] = Camera(id, model, width, height, params)
- points3D[point3D_id] = Point3D(id, xyz, rgb, error, image_ids, point2D_idxs)
"""
def get_all_image_names(self) -> List[str]:
"""
Get all image names.
"""
image_names = [image.name for image in self.images.values()]
image_names.sort()
return image_names
def get_query_image_id(self, image_name: str) -> int:
"""
Get image ID from image name.
"""
image_name = image_name.split('/')[-1]
image_id = [k for k, v in self.images.items() if v.name == image_name][0]
return image_id
def get_query_pose(self, image_id: int) -> np.ndarray:
"""
Get pose of image from database.
"""
image = self.images[image_id]
pose = np.concatenate([image.tvec, image.qvec])
assert pose.shape == (7,), pose.shape
return pose
def get_query_intrinsics(self, image_id: int) -> Tuple[str, int, int, np.ndarray]:
"""
Get intrinsics of image from database.
Output: camera model, camera parameters, image width, image height
"""
image = self.images[image_id]
camera_id = image.camera_id
camera = self.cameras[camera_id]
camera_model: str = camera.model
w: int = camera.width
h: int = camera.height
camera_params: np.ndarray = camera.params
return camera_model, w, h, camera_params
def write_query_intrinsics_text_file(
self,
path_to_output: Path,
query_names: List[str],
file_name: str = 'queries.txt',
):
"""
Write queries text file in inputs directory (for use with MeshLoc).
Format in each line: query_name, camera_model, w, h, camera_params
"""
if not file_name.endswith('.txt'):
file_name += '.txt'
with open(path_to_output / file_name, 'w') as f:
for query_name in query_names:
query_id = self.get_query_image_id(query_name)
(camera_model, w, h, camera_params) = self.get_query_intrinsics(query_id)
f.write(f"{query_name} {camera_model} {w} {h} {' '.join(map(str, camera_params))}\n")
def write_query_poses_text_file(
self,
path_to_output: Path,
query_names: List[str],
file_name: str = 'cam_sfm_poses.txt',
):
"""
Write poses ground truth text file in outputs directory (for use with MeshLoc).
Format in each line: query_name, pose
"""
if not file_name.endswith('.txt'):
file_name += '.txt'
with open(path_to_output / file_name, 'w') as f:
for query_name in query_names:
query_id = self.get_query_image_id(query_name)
pose = self.get_query_pose(query_id)
f.write(f"{query_name} {' '.join(map(str, pose))}\n")
@staticmethod
def write_poses_text_file(
poses: Dict[str, np.ndarray],
path_to_output: Path,
file_name: str,
quaternion_first: bool, # for writing
):
"""
Write poses text file.
Assumes input with translation first.
"""
with open(path_to_output / file_name, 'w') as file:
for query_name, pose in poses.items():
tvec, qvec = pose[:3], pose[3:]
if quaternion_first:
file.write(f"{query_name} {' '.join(map(str, qvec))} {' '.join(map(str, tvec))}\n")
else:
file.write(f"{query_name} {' '.join(map(str, tvec))} {' '.join(map(str, qvec))}\n")
@staticmethod
def write_intrinsics_text_file(
intrinsics: Dict[str, Tuple[str, int, int, np.ndarray]],
path_to_output: Path,
file_name: str,
):
"""
Write intrinsics text file.
"""
with open(path_to_output / file_name, 'w') as file:
for query_name, (camera_model, w, h, camera_params) in intrinsics.items():
file.write(f"{query_name} {camera_model} {w} {h} {' '.join(map(str, camera_params))}\n")
class ColmapModelWriter:
"""
- images[image_id] = Image(id, qvec, tvec, camera_id, name, xys, point3D_ids)
- cameras[camera_id] = Camera(id, model, width, height, params)
"""
@staticmethod
def read_intrinsics_text_file(
path_to_intrinsics: Path,
intrinsics_file: str,
) -> Dict[str, Tuple[str, int, int, np.ndarray]]:
"""
Read intrinsics text file.
"""
intrinsics = {}
with open(path_to_intrinsics / intrinsics_file, 'r') as file:
intrinsics_data = file.readlines()
for line in intrinsics_data:
items = line.strip().split(' ')
query_name = items[0]
camera_model = items[1]
w, h = int(items[2]), int(items[3])
camera_params = np.array([float(i) for i in items[4:]])
intrinsics[query_name] = (camera_model, w, h, camera_params)
return intrinsics
@staticmethod
def read_poses_text_file(
path_to_poses: Path,
poses_file: str,
quaternion_first: bool,
) -> Dict[str, np.ndarray]:
"""
Read poses text file.
"""
poses = {}
with open(path_to_poses / poses_file, 'r') as file:
poses_data = file.readlines()
for line in poses_data:
items = line.strip().split(' ')
query_name = items[0]
pose = np.array([float(i) for i in items[1:]])
if quaternion_first:
qvec, tvec = pose[:4], pose[4:]
else:
tvec, qvec = pose[:3], pose[3:]
poses[query_name] = np.concatenate([tvec, qvec])
return poses
@staticmethod
def write_poses_dict_to_colmap_format(
output_path: Path,
poses: Dict[str, np.ndarray],
):
"""
Write poses to COLMAP format.
"""
images = {}
image_id = 0
for query_name, pose in poses.items():
image_id += 1
camera_id = image_id
tvec, qvec = pose[:3], pose[3:]
images[image_id] = BaseImage(
id=image_id,
qvec=qvec,
tvec=tvec,
camera_id=camera_id,
name=query_name,
xys=np.array([]),
point3D_ids=np.array([]),
)
write_images_binary(images, output_path / 'images.bin')
write_images_text(images, output_path / 'images.txt')
@staticmethod
def write_intrinsics_dict_to_colmap_format(
output_path: Path,
intrinsics: Dict[str, Tuple[str, int, int, np.ndarray]],
):
"""
Write intrinsics to COLMAP format.
"""
cameras = {}
camera_id = 0
for query_name, (camera_model, w, h, camera_params) in intrinsics.items():
camera_id += 1
cameras[camera_id] = Camera(
id=camera_id,
model=camera_model,
width=w,
height=h,
params=camera_params,
)
write_cameras_binary(cameras, output_path / 'cameras.bin')
write_cameras_text(cameras, output_path / 'cameras.txt')
@staticmethod
def write_poses_text_file_to_colmap_format(
path_to_poses: Path,
poses_file: str,
quaternion_first: bool,
):
"""
Write poses text file to COLMAP format.
"""
poses = ColmapModelWriter.read_poses_text_file(path_to_poses, poses_file, quaternion_first)
ColmapModelWriter.write_poses_dict_to_colmap_format(path_to_poses, poses)
@staticmethod
def write_intrinsics_text_file_to_colmap_format(
path_to_intrinsics: Path,
intrinsics_file: str,
):
"""
Write intrinsics text file to COLMAP format.
"""
intrinsics = ColmapModelWriter.read_intrinsics_text_file(path_to_intrinsics, intrinsics_file)
ColmapModelWriter.write_intrinsics_dict_to_colmap_format(path_to_intrinsics, intrinsics)
@staticmethod
def write_poses_and_intrinsics_text_files_to_colmap_format(
path_to_intrinsics: Path,
path_to_poses: Path,
poses_file: str,
intrinsincs_file: str,
quaternion_first: bool,
):
"""
Write query poses and intrinsics to COLMAP format.
Uses same id for camera and image.
"""
ColmapModelWriter.write_intrinsics_text_file_to_colmap_format(path_to_intrinsics, intrinsincs_file)
ColmapModelWriter.write_poses_text_file_to_colmap_format(path_to_poses, poses_file, quaternion_first)
class ColmapModelConverter:
"""
Convert COLMAP model data between text and binary formats.
"""
@staticmethod
def convert_text_to_binary(
path_to_text: Path,
path_to_binary: Path,
):
"""
Convert text to binary files.
"""
path_to_cameras = path_to_binary / 'cameras.txt'
print(path_to_cameras)
if (path_to_text / 'cameras.txt').exists():
cameras = read_cameras_text(path_to_text / 'cameras.txt')
if not (path_to_binary / 'cameras.bin').exists():
write_cameras_binary(cameras, path_to_binary / 'cameras.bin')
if (path_to_text / 'images.txt').exists():
images = read_images_text(path_to_text / 'images.txt')
if not (path_to_binary / 'images.bin').exists():
write_images_binary(images, path_to_binary / 'images.bin')
if (path_to_text / 'points3D.txt').exists():
points3D = read_points3D_text(path_to_text / 'points3D.txt')
if not (path_to_binary / 'points3D.bin').exists():
write_points3D_binary(points3D, path_to_binary / 'points3D.bin')
@staticmethod
def convert_binary_to_text(
path_to_binary: Path,
path_to_text: Path,
):
"""
Convert binary to text files.
"""
if (path_to_binary / 'cameras.bin').exists():
cameras = read_cameras_binary(path_to_binary / 'cameras.bin')
if not (path_to_text / 'cameras.txt').exists():
write_cameras_text(cameras, path_to_text / 'cameras.txt')
if (path_to_binary / 'images.bin').exists():
images = read_images_binary(path_to_binary / 'images.bin')
if not (path_to_text / 'images.txt').exists():
write_images_text(images, path_to_text / 'images.txt')
if (path_to_binary / 'points3D.bin').exists():
points3D = read_points3D_binary(path_to_binary / 'points3D.bin')
if not (path_to_text / 'points3D.txt').exists():
write_points3D_text(points3D, path_to_text / 'points3D.txt')
if __name__ == '__main__':
pass
# from data_new import Model, CadModel
# model = Model('Notre Dame')
# cad_model = CadModel(model, 'B')
# poses_file = '25_superglue_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt'
# ColmapModelWriter.write_query_poses_to_colmap_format(
# path_to_query=cad_model.path_to_query,
# path_to_poses=cad_model.path_to_meshloc_out,
# poses_file=poses_file,
# quaternion_first=True,
# )
# ColmapModelWriter.write_query_poses_to_colmap_format(
# path_to_query=cad_model.path_to_query,
# path_to_poses=cad_model.path_to_ground_truth,
# poses_file='cam_sfm_poses.txt',
# quaternion_first=False,
# )
# ColmapModelWriter.write_query_poses_to_colmap_format(
# path_to_query=Path('/Users/eric/Developer/meshloc_dataset/aachen_day_night_v11/'),
# path_to_poses=Path('/Users/eric/Developer/meshloc_output/aachen_day_night_v11/superglue/experiment_output/'),
# poses_file='50_superglue_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt',
# quaternion_first=True,
# )
# path_to_text = Path('/Users/eric/Downloads/colmap visualization/Aachen/input MeshLoc/')
# path_to_binary = path_to_text
# ColmapModelConverter.convert_text_to_binary(path_to_text, path_to_binary)
# path_to_binary = Path('/Users/eric/Downloads/colmap visualization/Notre Dame B/output queries MeshLoc/')
# path_to_text = path_to_binary
# ColmapModelConverter.convert_binary_to_text(path_to_binary, path_to_text)
'''
Notre Dame B
'''
# output_path = Path('/Users/eric/Documents/Studies/MSc Robotics/Thesis/Evaluation/notre_dame_B/outputs/meshloc_out/patch2pix/')
# poses_file = '25_patch2pix_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt'
# intrinsics_file = 'queries.txt'
# ColmapModelWriter.write_poses_text_file_to_colmap_format(output_path, poses_file, quaternion_first=True)
# ColmapModelWriter.write_intrinsics_text_file_to_colmap_format(output_path, intrinsics_file)
'''
Notre Dame E
'''
# output_path = Path('/Users/eric/Documents/Studies/MSc Robotics/Thesis/Evaluation/notre_dame_E/outputs/meshloc_out/patch2pix/')
# poses_file = '20_patch2pix_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt'
# intrinsics_file = 'queries.txt'
# ColmapModelWriter.write_poses_text_file_to_colmap_format(output_path, poses_file, quaternion_first=True)
# ColmapModelWriter.write_intrinsics_text_file_to_colmap_format(output_path, intrinsics_file)
'''
Aachen Day-Night
- Patch2Pix
- SuperGlue
'''
# output_path = Path('/Users/eric/Developer/meshloc_output/aachen_day_night_v11/patch2pix/experiment_output/')
# poses_file = '50_patch2pix_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt'
# intrinsics_file = 'night_time_queries_with_intrinsics_800_basenames.txt'
# ColmapModelWriter.write_poses_text_file_to_colmap_format(output_path, poses_file, quaternion_first=True)
# ColmapModelWriter.write_intrinsics_text_file_to_colmap_format(output_path, intrinsics_file)
# output_path = Path('/Users/eric/Developer/meshloc_output/aachen_day_night_v11/superglue/experiment_output/')
# poses_file = '50_superglue_aachen_v1_1__20.0_keypoint_clusters_POSELIB+REF_min_10000_max_100000_ref_1.0_0.25_bias_0.0_0.0.txt'
# intrinsics_file = 'night_time_queries_with_intrinsics_800_basenames.txt'
# ColmapModelWriter.write_poses_text_file_to_colmap_format(output_path, poses_file, quaternion_first=True)
# ColmapModelWriter.write_intrinsics_text_file_to_colmap_format(output_path, intrinsics_file)