Colmap根据已知相机参数进行重建

方法介绍

如果我们有一个图像序列,但是不知道每个图像的相机外参,那么我们可以使用COLMAP来帮助我们恢复相机外参,同时还可以利用SfM来恢复出场景点云。

不过这里我们关注的是另外一种情况,我们有图像序列,同时还知道每个图像的相机内外参数。我们希望能够在给定的相机内外参数下来重建场景点云。官方文档中给出了相应的解决方案,这里给出更加详细的操作流程。

在整个过程中,我们需要构建出三个(两个有内容)关键文件,cameras.txt,images.txt,points3D.txt。

首先,根据已知的相机内参,在colmap的工作目录下构建出cameras.txt,其中的格式需要与官方文档中说明的保持一致:

1
2
3
4
5
# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[fx,fy,cx,cy]
1 PINHOLE 1280 720 771.904 771.896 639.993 360.001

# OPENCV会增加额外的参数k1,k2,p1,p2,如下所示
# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[fx,fy,cx,cy,k1,k2,p1,p2]

然后运行feature extractor和exhaustive_matcher命令,分别进行图像的特征抽取和特征匹配。这两步不需要相机位姿,仅需要在images目录下存放相应的图像文件即可。命令运行完成之后,在colmap的工作目录下会出现一个database.db文件,即相关数据库。

默认情况下,colmap使用默认相机模型填充database.db中的cameras table,我们需要将真实的相机内参导入并更新database.db。一种方法是通过Colmap UI来更新,不过这种方式需要人工手动进行。另一种方式是参考官方提供的database.py来完成相应的操作。实际上需要完成的操作也非常简单,只需要执行sql语句来更新database中cameras条目的记录即可。不过需要注意的是这里相机类型和具体label的对应。

接下来需要构建出images.txt文件。在colmap默认读取images文件夹下图像得到的database.db中,image_id和image_name的对应关系是随机的,而images.txt中的内容需要保持与database.db中对应关系的一致。因此我们需要首先从database.db中读取现有的对应关系,然后根据这个对应关系再来构建images.txt。这一步骤实际上也比较简单,涉及到SELECT SQL语句。从database.db中导出的images list中只有image_id和image_name的对应关系,没有相机外参。根据这个list来创建images.txt,其中image_id和image_name需要保持对应关系,同时增加已知的相机外参,即可构建出images.txt

images.txt每一行的格式如下:

1
2
3
4
# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME
1 0.430115 0.411564 0.555504 -0.580543 10468.491287 380.313066 1720.465175 1 image001.jpg

2 0.309712 0.337960 0.655221 -0.600456 10477.663284 446.4208 -1633.886712 2 image002.jpg

当然需要注意每隔一行中间需要留空。

这里图像的四元数和平移向量需要从w2c矩阵中获得。

再然后在colmap工作目录下创建一个空的points3D.txt

最后,执行接下来的相关命令即可,例如point_triangulator。

参考代码

这里给出修改适配后的参考代码database.py,与官方实现不同的地方在于:

  • 增加了更新cameras table的方法update_camera和查询images对应关系的方法export_images_list
  • 增加了参数类CameraParamImageParam,表征txt每行字符串和相关参数的映射关系
  • 增加了从colmap工作目录出发完成的camera table更新操作和images txt导出操作
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
import os
import sys
import sqlite3
import numpy as np


IS_PYTHON3 = sys.version_info[0] >= 3

MAX_IMAGE_ID = 2**31 - 1

CREATE_CAMERAS_TABLE = """CREATE TABLE IF NOT EXISTS cameras (
camera_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
model INTEGER NOT NULL,
width INTEGER NOT NULL,
height INTEGER NOT NULL,
params BLOB,
prior_focal_length INTEGER NOT NULL)"""

CREATE_DESCRIPTORS_TABLE = """CREATE TABLE IF NOT EXISTS descriptors (
image_id INTEGER PRIMARY KEY NOT NULL,
rows INTEGER NOT NULL,
cols INTEGER NOT NULL,
data BLOB,
FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)"""

CREATE_IMAGES_TABLE = """CREATE TABLE IF NOT EXISTS images (
image_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL UNIQUE,
camera_id INTEGER NOT NULL,
prior_qw REAL,
prior_qx REAL,
prior_qy REAL,
prior_qz REAL,
prior_tx REAL,
prior_ty REAL,
prior_tz REAL,
CONSTRAINT image_id_check CHECK(image_id >= 0 and image_id < {}),
FOREIGN KEY(camera_id) REFERENCES cameras(camera_id))
""".format(
MAX_IMAGE_ID
)

CREATE_POSE_PRIORS_TABLE = """CREATE TABLE IF NOT EXISTS pose_priors (
image_id INTEGER PRIMARY KEY NOT NULL,
position BLOB,
coordinate_system INTEGER NOT NULL,
FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)"""

CREATE_TWO_VIEW_GEOMETRIES_TABLE = """
CREATE TABLE IF NOT EXISTS two_view_geometries (
pair_id INTEGER PRIMARY KEY NOT NULL,
rows INTEGER NOT NULL,
cols INTEGER NOT NULL,
data BLOB,
config INTEGER NOT NULL,
F BLOB,
E BLOB,
H BLOB,
qvec BLOB,
tvec BLOB)
"""

CREATE_KEYPOINTS_TABLE = """CREATE TABLE IF NOT EXISTS keypoints (
image_id INTEGER PRIMARY KEY NOT NULL,
rows INTEGER NOT NULL,
cols INTEGER NOT NULL,
data BLOB,
FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)
"""

CREATE_MATCHES_TABLE = """CREATE TABLE IF NOT EXISTS matches (
pair_id INTEGER PRIMARY KEY NOT NULL,
rows INTEGER NOT NULL,
cols INTEGER NOT NULL,
data BLOB)"""

CREATE_NAME_INDEX = "CREATE UNIQUE INDEX IF NOT EXISTS index_name ON images(name)"

CREATE_ALL = "; ".join(
[
CREATE_CAMERAS_TABLE,
CREATE_IMAGES_TABLE,
CREATE_POSE_PRIORS_TABLE,
CREATE_KEYPOINTS_TABLE,
CREATE_DESCRIPTORS_TABLE,
CREATE_MATCHES_TABLE,
CREATE_TWO_VIEW_GEOMETRIES_TABLE,
CREATE_NAME_INDEX,
]
)

CAM_MODEL_DICT = {
"SIMPLE_PINHOLE": 0,
"PINHOLE": 1,
"SIMPLE_RADIAL": 2,
"RADIAL": 3,
"OPENCV": 4,
"FULL_OPENCV": 5,
"SIMPLE_RADIAL_FISHEYE": 6,
"RADIAL_FISHEYE": 7,
"OPENCV_FISHEYE": 8,
"FOV": 9,
"THIN_PRISM_FISHEYE": 10,
}


def image_ids_to_pair_id(image_id1, image_id2):
if image_id1 > image_id2:
image_id1, image_id2 = image_id2, image_id1
return image_id1 * MAX_IMAGE_ID + image_id2


def pair_id_to_image_ids(pair_id):
image_id2 = pair_id % MAX_IMAGE_ID
image_id1 = (pair_id - image_id2) / MAX_IMAGE_ID
return image_id1, image_id2


def array_to_blob(array):
if IS_PYTHON3:
return array.tostring()
else:
return np.getbuffer(array)


def blob_to_array(blob, dtype, shape=(-1,)):
if IS_PYTHON3:
return np.fromstring(blob, dtype=dtype).reshape(*shape)
else:
return np.frombuffer(blob, dtype=dtype).reshape(*shape)


class COLMAPDatabase(sqlite3.Connection):
@staticmethod
def connect(database_path):
return sqlite3.connect(database_path, factory=COLMAPDatabase)

def __init__(self, *args, **kwargs):
super(COLMAPDatabase, self).__init__(*args, **kwargs)

self.create_tables = lambda: self.executescript(CREATE_ALL)
self.create_cameras_table = lambda: self.executescript(CREATE_CAMERAS_TABLE)
self.create_descriptors_table = lambda: self.executescript(
CREATE_DESCRIPTORS_TABLE
)
self.create_images_table = lambda: self.executescript(CREATE_IMAGES_TABLE)
self.create_pose_priors_table = lambda: self.executescript(
CREATE_POSE_PRIORS_TABLE
)
self.create_two_view_geometries_table = lambda: self.executescript(
CREATE_TWO_VIEW_GEOMETRIES_TABLE
)
self.create_keypoints_table = lambda: self.executescript(CREATE_KEYPOINTS_TABLE)
self.create_matches_table = lambda: self.executescript(CREATE_MATCHES_TABLE)
self.create_name_index = lambda: self.executescript(CREATE_NAME_INDEX)

def add_camera(
self,
model,
width,
height,
params,
prior_focal_length=False,
camera_id=None,
):
params = np.asarray(params, np.float64)
cursor = self.execute(
"INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)",
(
camera_id,
model,
width,
height,
array_to_blob(params),
prior_focal_length,
),
)
return cursor.lastrowid

def add_image(
self,
name,
camera_id,
prior_q=np.full(4, np.nan),
prior_t=np.full(3, np.nan),
image_id=None,
):
cursor = self.execute(
"INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
image_id,
name,
camera_id,
prior_q[0],
prior_q[1],
prior_q[2],
prior_q[3],
prior_t[0],
prior_t[1],
prior_t[2],
),
)
return cursor.lastrowid

def add_pose_prior(self, image_id, position, coordinate_system=-1):
position = np.asarray(position, dtype=np.float64)
self.execute(
"INSERT INTO pose_priors VALUES (?, ?, ?)",
(image_id, array_to_blob(position), coordinate_system),
)

def add_keypoints(self, image_id, keypoints):
assert len(keypoints.shape) == 2
assert keypoints.shape[1] in [2, 4, 6]

keypoints = np.asarray(keypoints, np.float32)
self.execute(
"INSERT INTO keypoints VALUES (?, ?, ?, ?)",
(image_id,) + keypoints.shape + (array_to_blob(keypoints),),
)

def add_descriptors(self, image_id, descriptors):
descriptors = np.ascontiguousarray(descriptors, np.uint8)
self.execute(
"INSERT INTO descriptors VALUES (?, ?, ?, ?)",
(image_id,) + descriptors.shape + (array_to_blob(descriptors),),
)

def add_matches(self, image_id1, image_id2, matches):
assert len(matches.shape) == 2
assert matches.shape[1] == 2

if image_id1 > image_id2:
matches = matches[:, ::-1]

pair_id = image_ids_to_pair_id(image_id1, image_id2)
matches = np.asarray(matches, np.uint32)
self.execute(
"INSERT INTO matches VALUES (?, ?, ?, ?)",
(pair_id,) + matches.shape + (array_to_blob(matches),),
)

def add_two_view_geometry(
self,
image_id1,
image_id2,
matches,
F=np.eye(3),
E=np.eye(3),
H=np.eye(3),
qvec=np.array([1.0, 0.0, 0.0, 0.0]),
tvec=np.zeros(3),
config=2,
):
assert len(matches.shape) == 2
assert matches.shape[1] == 2

if image_id1 > image_id2:
matches = matches[:, ::-1]

pair_id = image_ids_to_pair_id(image_id1, image_id2)
matches = np.asarray(matches, np.uint32)
F = np.asarray(F, dtype=np.float64)
E = np.asarray(E, dtype=np.float64)
H = np.asarray(H, dtype=np.float64)
qvec = np.asarray(qvec, dtype=np.float64)
tvec = np.asarray(tvec, dtype=np.float64)
self.execute(
"INSERT INTO two_view_geometries VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(pair_id,)
+ matches.shape
+ (
array_to_blob(matches),
config,
array_to_blob(F),
array_to_blob(E),
array_to_blob(H),
array_to_blob(qvec),
array_to_blob(tvec),
),
)

def update_camera(self, model, width, height, params, camera_id=None):
params = np.asarray(params, np.float64)
cursor = self.execute(
"UPDATE cameras SET model=?, width=?, height=?, params=?, prior_focal_length=True WHERE camera_id=?",
(model, width, height, array_to_blob(params), camera_id),
)
return cursor.lastrowid

def export_images_list(self):
rows = self.execute("SELECT image_id, name FROM images").fetchall()
result = [list(row) for row in rows]
return result


class CameraParam:
def __init__(self, params_line):
params = params_line.split(" ")
self.camera_id = int(params[0])
camera_model = str(params[1])
self.model = CAM_MODEL_DICT[camera_model]
self.width = int(params[2])
self.height = int(params[3])
self.params = np.array([float(i) for i in params[4:]])


class ImageParam:
def __init__(self, params_line):
params = params_line.split(" ")
self.image_id = int(params[0])
self.prior_q = np.array([float(i) for i in params[1:5]])
self.prior_t = np.array([float(i) for i in params[5:8]])
self.camera_id = int(params[8])
self.name = params[9]


def export_images_txt_from_database(colmap_project_path):
database_path = os.path.join(colmap_project_path, "database.db")
db = COLMAPDatabase.connect(database_path)
result = db.export_images_list()
db.close()
return result


def update_database_from_exist_param(colmap_project_path):
database_path = os.path.join(colmap_project_path, "database.db")

# Open the database.
db = COLMAPDatabase.connect(database_path)

# update cameras from existed cameras.txt
cameras_txt_path = os.path.join(colmap_project_path, "cameras.txt")
assert os.path.exists(cameras_txt_path)
with open(cameras_txt_path, "r") as f:
for line in f.readlines():
camera_param = CameraParam(line)
db.update_camera(
model=camera_param.model,
width=camera_param.width,
height=camera_param.height,
params=camera_param.params,
camera_id=camera_param.camera_id,
)
# Commit the data to the file.
db.commit()
db.close()

参考文章

  1. Reconstruct Sparse/Dense Model from known camera poses — COLMAP 3.11-dev documentation
  2. COLMAP已知相机内外参数重建稀疏/稠密模型 - thronsbird - 博客园
  3. COLMAP简易教程(命令行模式) - coffee_tea_or_me - 博客园

Colmap根据已知相机参数进行重建
http://example.com/2024/08/02/Colmap根据已知相机参数进行重建/
作者
EverNorif
发布于
2024年8月2日
许可协议