Travis Driver commited on
Commit
9e4b152
Β·
1 Parent(s): d86ebae

Add example

Browse files
Files changed (40) hide show
  1. cornelia_images.zip β†’ cornelia_images_uncalibrated.zip +0 -0
  2. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0008195_11275021648F1G.png +0 -0
  3. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0008203_11275022217F1G.png +0 -0
  4. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009871_11283182406F1E.png +0 -0
  5. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009872_11283182806F1E.png +0 -0
  6. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009873_11283183206F1E.png +0 -0
  7. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009874_11283183606F1E.png +0 -0
  8. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010191_11286212239F1G.png +0 -0
  9. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010192_11286212639F1G.png +0 -0
  10. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010193_11286213039F1G.png +0 -0
  11. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010897_11294002155F1D.png +0 -0
  12. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010898_11294002554F1D.png +0 -0
  13. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010899_11294002954F1D.png +0 -0
  14. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011423_11299032813F1E.png +0 -0
  15. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011424_11299033213F1E.png +0 -0
  16. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011425_11299033613F1E.png +0 -0
  17. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0013975_11304061037F1D.png +0 -0
  18. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0013990_11304061745F1D.png +0 -0
  19. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027308_12176082417F1B.png +0 -0
  20. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027309_12176083017F1B.png +0 -0
  21. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027981_12183111850F1D.png +0 -0
  22. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027982_12183112250F1D.png +0 -0
  23. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028154_12185004126F1D.png +0 -0
  24. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028302_12186141628F1D.png +0 -0
  25. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028303_12186142228F1D.png +0 -0
  26. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028765_12191171942F1B.png +0 -0
  27. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028766_12191172542F1B.png +0 -0
  28. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0029464_12198202136F1E.png +0 -0
  29. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0031559_12205122415F1C.png +0 -0
  30. {cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0031574_12205123303F1C.png +0 -0
  31. example.ipynb +0 -0
  32. utils/.DS_Store +0 -0
  33. utils/__init__.py +0 -0
  34. utils/__pycache__/__init__.cpython-38.pyc +0 -0
  35. utils/__pycache__/read_write_model.cpython-38.pyc +0 -0
  36. utils/__pycache__/reflectance.cpython-38.pyc +0 -0
  37. utils/__pycache__/spc_types.cpython-38.pyc +0 -0
  38. utils/read_write_model.py +507 -0
  39. utils/reflectance.py +51 -0
  40. utils/spc_types.py +253 -0
cornelia_images.zip β†’ cornelia_images_uncalibrated.zip RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0008195_11275021648F1G.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0008203_11275022217F1G.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009871_11283182406F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009872_11283182806F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009873_11283183206F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0009874_11283183606F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010191_11286212239F1G.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010192_11286212639F1G.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010193_11286213039F1G.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010897_11294002155F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010898_11294002554F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0010899_11294002954F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011423_11299032813F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011424_11299033213F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0011425_11299033613F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0013975_11304061037F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0013990_11304061745F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027308_12176082417F1B.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027309_12176083017F1B.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027981_12183111850F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0027982_12183112250F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028154_12185004126F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028302_12186141628F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028303_12186142228F1D.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028765_12191171942F1B.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0028766_12191172542F1B.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0029464_12198202136F1E.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0031559_12205122415F1C.png RENAMED
File without changes
{cornelia_images β†’ cornelia_images_uncalibrated}/FC21B0031574_12205123303F1C.png RENAMED
File without changes
example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
utils/.DS_Store ADDED
Binary file (6.15 kB). View file
 
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (154 Bytes). View file
 
utils/__pycache__/read_write_model.cpython-38.pyc ADDED
Binary file (14.5 kB). View file
 
utils/__pycache__/reflectance.cpython-38.pyc ADDED
Binary file (1.66 kB). View file
 
utils/__pycache__/spc_types.cpython-38.pyc ADDED
Binary file (6.93 kB). View file
 
utils/read_write_model.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, ETH Zurich and UNC Chapel Hill.
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are met:
6
+ #
7
+ # * Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # * Redistributions in binary form must reproduce the above copyright
11
+ # notice, this list of conditions and the following disclaimer in the
12
+ # documentation and/or other materials provided with the distribution.
13
+ #
14
+ # * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15
+ # its contributors may be used to endorse or promote products derived
16
+ # from this software without specific prior written permission.
17
+ #
18
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+ #
30
+ # Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
31
+
32
+ import os
33
+ import collections
34
+ import numpy as np
35
+ import struct
36
+ import argparse
37
+
38
+
39
+ CameraModel = collections.namedtuple("CameraModel", ["model_id", "model_name", "num_params"])
40
+ Camera = collections.namedtuple("Camera", ["id", "model", "width", "height", "params"])
41
+ BaseImage = collections.namedtuple("Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
42
+ Point3D = collections.namedtuple("Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
43
+
44
+
45
+ class Image(BaseImage):
46
+ def qvec2rotmat(self):
47
+ return qvec2rotmat(self.qvec)
48
+
49
+
50
+ CAMERA_MODELS = {
51
+ CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
52
+ CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
53
+ CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
54
+ CameraModel(model_id=3, model_name="RADIAL", num_params=5),
55
+ CameraModel(model_id=4, model_name="OPENCV", num_params=8),
56
+ CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
57
+ CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
58
+ CameraModel(model_id=7, model_name="FOV", num_params=5),
59
+ CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
60
+ CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
61
+ CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12),
62
+ }
63
+ CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model) for camera_model in CAMERA_MODELS])
64
+ CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model) for camera_model in CAMERA_MODELS])
65
+
66
+
67
+ def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
68
+ """Read and unpack the next bytes from a binary file.
69
+ :param fid:
70
+ :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
71
+ :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
72
+ :param endian_character: Any of {@, =, <, >, !}
73
+ :return: Tuple of read and unpacked values.
74
+ """
75
+ data = fid.read(num_bytes)
76
+ return struct.unpack(endian_character + format_char_sequence, data)
77
+
78
+
79
+ def write_next_bytes(fid, data, format_char_sequence, endian_character="<"):
80
+ """pack and write to a binary file.
81
+ :param fid:
82
+ :param data: data to send, if multiple elements are sent at the same time,
83
+ they should be encapsuled either in a list or a tuple
84
+ :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
85
+ should be the same length as the data list or tuple
86
+ :param endian_character: Any of {@, =, <, >, !}
87
+ """
88
+ if isinstance(data, (list, tuple)):
89
+ bytes = struct.pack(endian_character + format_char_sequence, *data)
90
+ else:
91
+ bytes = struct.pack(endian_character + format_char_sequence, data)
92
+ fid.write(bytes)
93
+
94
+
95
+ def read_cameras_text(path):
96
+ """
97
+ see: src/base/reconstruction.cc
98
+ void Reconstruction::WriteCamerasText(const std::string& path)
99
+ void Reconstruction::ReadCamerasText(const std::string& path)
100
+ """
101
+ cameras = {}
102
+ with open(path, "r") as fid:
103
+ while True:
104
+ line = fid.readline()
105
+ if not line:
106
+ break
107
+ line = line.strip()
108
+ if len(line) > 0 and line[0] != "#":
109
+ elems = line.split()
110
+ camera_id = int(elems[0])
111
+ model = elems[1]
112
+ width = int(elems[2])
113
+ height = int(elems[3])
114
+ params = np.array(tuple(map(float, elems[4:])))
115
+ cameras[camera_id] = Camera(id=camera_id, model=model, width=width, height=height, params=params)
116
+ return cameras
117
+
118
+
119
+ def read_cameras_binary(path_to_model_file):
120
+ """
121
+ see: src/base/reconstruction.cc
122
+ void Reconstruction::WriteCamerasBinary(const std::string& path)
123
+ void Reconstruction::ReadCamerasBinary(const std::string& path)
124
+ """
125
+ cameras = {}
126
+ with open(path_to_model_file, "rb") as fid:
127
+ num_cameras = read_next_bytes(fid, 8, "Q")[0]
128
+ for _ in range(num_cameras):
129
+ camera_properties = read_next_bytes(fid, num_bytes=24, format_char_sequence="iiQQ")
130
+ camera_id = camera_properties[0]
131
+ model_id = camera_properties[1]
132
+ model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
133
+ width = camera_properties[2]
134
+ height = camera_properties[3]
135
+ num_params = CAMERA_MODEL_IDS[model_id].num_params
136
+ params = read_next_bytes(fid, num_bytes=8 * num_params, format_char_sequence="d" * num_params)
137
+ cameras[camera_id] = Camera(
138
+ id=camera_id, model=model_name, width=width, height=height, params=np.array(params)
139
+ )
140
+ assert len(cameras) == num_cameras
141
+ return cameras
142
+
143
+
144
+ def write_cameras_text(cameras, path):
145
+ """
146
+ see: src/base/reconstruction.cc
147
+ void Reconstruction::WriteCamerasText(const std::string& path)
148
+ void Reconstruction::ReadCamerasText(const std::string& path)
149
+ """
150
+ HEADER = (
151
+ "# Camera list with one line of data per camera:\n"
152
+ + "# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n"
153
+ + "# Number of cameras: {}\n".format(len(cameras))
154
+ )
155
+ with open(path, "w") as fid:
156
+ fid.write(HEADER)
157
+ for _, cam in cameras.items():
158
+ to_write = [cam.id, cam.model, cam.width, cam.height, *cam.params]
159
+ line = " ".join([str(elem) for elem in to_write])
160
+ fid.write(line + "\n")
161
+
162
+
163
+ def write_cameras_binary(cameras, path_to_model_file):
164
+ """
165
+ see: src/base/reconstruction.cc
166
+ void Reconstruction::WriteCamerasBinary(const std::string& path)
167
+ void Reconstruction::ReadCamerasBinary(const std::string& path)
168
+ """
169
+ with open(path_to_model_file, "wb") as fid:
170
+ write_next_bytes(fid, len(cameras), "Q")
171
+ for _, cam in cameras.items():
172
+ model_id = CAMERA_MODEL_NAMES[cam.model].model_id
173
+ camera_properties = [cam.id, model_id, cam.width, cam.height]
174
+ write_next_bytes(fid, camera_properties, "iiQQ")
175
+ for p in cam.params:
176
+ write_next_bytes(fid, float(p), "d")
177
+ return cameras
178
+
179
+
180
+ def read_images_text(path):
181
+ """
182
+ see: src/base/reconstruction.cc
183
+ void Reconstruction::ReadImagesText(const std::string& path)
184
+ void Reconstruction::WriteImagesText(const std::string& path)
185
+ """
186
+ images = {}
187
+ with open(path, "r") as fid:
188
+ while True:
189
+ line = fid.readline()
190
+ if not line:
191
+ break
192
+ line = line.strip()
193
+ if len(line) > 0 and line[0] != "#":
194
+ elems = line.split()
195
+ image_id = int(elems[0])
196
+ qvec = np.array(tuple(map(float, elems[1:5])))
197
+ tvec = np.array(tuple(map(float, elems[5:8])))
198
+ camera_id = int(elems[8])
199
+ image_name = elems[9]
200
+ elems = fid.readline().split()
201
+ xys = np.column_stack([tuple(map(float, elems[0::3])), tuple(map(float, elems[1::3]))])
202
+ point3D_ids = np.array(tuple(map(int, elems[2::3])))
203
+ images[image_id] = Image(
204
+ id=image_id,
205
+ qvec=qvec,
206
+ tvec=tvec,
207
+ camera_id=camera_id,
208
+ name=image_name,
209
+ xys=xys,
210
+ point3D_ids=point3D_ids,
211
+ )
212
+ return images
213
+
214
+
215
+ def read_images_binary(path_to_model_file):
216
+ """
217
+ see: src/base/reconstruction.cc
218
+ void Reconstruction::ReadImagesBinary(const std::string& path)
219
+ void Reconstruction::WriteImagesBinary(const std::string& path)
220
+ """
221
+ images = {}
222
+ with open(path_to_model_file, "rb") as fid:
223
+ num_reg_images = read_next_bytes(fid, 8, "Q")[0]
224
+ for _ in range(num_reg_images):
225
+ binary_image_properties = read_next_bytes(fid, num_bytes=64, format_char_sequence="idddddddi")
226
+ image_id = binary_image_properties[0]
227
+ qvec = np.array(binary_image_properties[1:5])
228
+ tvec = np.array(binary_image_properties[5:8])
229
+ camera_id = binary_image_properties[8]
230
+ image_name = ""
231
+ current_char = read_next_bytes(fid, 1, "c")[0]
232
+ while current_char != b"\x00": # look for the ASCII 0 entry
233
+ image_name += current_char.decode("utf-8")
234
+ current_char = read_next_bytes(fid, 1, "c")[0]
235
+ num_points2D = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
236
+ x_y_id_s = read_next_bytes(fid, num_bytes=24 * num_points2D, format_char_sequence="ddq" * num_points2D)
237
+ xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])), tuple(map(float, x_y_id_s[1::3]))])
238
+ point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
239
+ images[image_id] = Image(
240
+ id=image_id,
241
+ qvec=qvec,
242
+ tvec=tvec,
243
+ camera_id=camera_id,
244
+ name=image_name,
245
+ xys=xys,
246
+ point3D_ids=point3D_ids,
247
+ )
248
+ return images
249
+
250
+
251
+ def write_images_text(images, path):
252
+ """
253
+ see: src/base/reconstruction.cc
254
+ void Reconstruction::ReadImagesText(const std::string& path)
255
+ void Reconstruction::WriteImagesText(const std::string& path)
256
+ """
257
+ if len(images) == 0:
258
+ mean_observations = 0
259
+ else:
260
+ mean_observations = sum((len(img.point3D_ids) for _, img in images.items())) / len(images)
261
+ HEADER = (
262
+ "# Image list with two lines of data per image:\n"
263
+ + "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n"
264
+ + "# POINTS2D[] as (X, Y, POINT3D_ID)\n"
265
+ + "# Number of images: {}, mean observations per image: {}\n".format(len(images), mean_observations)
266
+ )
267
+
268
+ with open(path, "w") as fid:
269
+ fid.write(HEADER)
270
+ for _, img in images.items():
271
+ image_header = [img.id, *img.qvec, *img.tvec, img.camera_id, img.name]
272
+ first_line = " ".join(map(str, image_header))
273
+ fid.write(first_line + "\n")
274
+
275
+ points_strings = []
276
+ for xy, point3D_id in zip(img.xys, img.point3D_ids):
277
+ points_strings.append(" ".join(map(str, [*xy, point3D_id])))
278
+ fid.write(" ".join(points_strings) + "\n")
279
+
280
+
281
+ def write_images_binary(images, path_to_model_file):
282
+ """
283
+ see: src/base/reconstruction.cc
284
+ void Reconstruction::ReadImagesBinary(const std::string& path)
285
+ void Reconstruction::WriteImagesBinary(const std::string& path)
286
+ """
287
+ with open(path_to_model_file, "wb") as fid:
288
+ write_next_bytes(fid, len(images), "Q")
289
+ for _, img in images.items():
290
+ write_next_bytes(fid, img.id, "i")
291
+ write_next_bytes(fid, img.qvec.tolist(), "dddd")
292
+ write_next_bytes(fid, img.tvec.tolist(), "ddd")
293
+ write_next_bytes(fid, img.camera_id, "i")
294
+ for char in img.name:
295
+ write_next_bytes(fid, char.encode("utf-8"), "c")
296
+ write_next_bytes(fid, b"\x00", "c")
297
+ write_next_bytes(fid, len(img.point3D_ids), "Q")
298
+ for xy, p3d_id in zip(img.xys, img.point3D_ids):
299
+ write_next_bytes(fid, [*xy, p3d_id], "ddq")
300
+
301
+
302
+ def read_points3D_text(path):
303
+ """
304
+ see: src/base/reconstruction.cc
305
+ void Reconstruction::ReadPoints3DText(const std::string& path)
306
+ void Reconstruction::WritePoints3DText(const std::string& path)
307
+ """
308
+ points3D = {}
309
+ with open(path, "r") as fid:
310
+ while True:
311
+ line = fid.readline()
312
+ if not line:
313
+ break
314
+ line = line.strip()
315
+ if len(line) > 0 and line[0] != "#":
316
+ elems = line.split()
317
+ point3D_id = int(elems[0])
318
+ xyz = np.array(tuple(map(float, elems[1:4])))
319
+ rgb = np.array(tuple(map(int, elems[4:7])))
320
+ error = float(elems[7])
321
+ image_ids = np.array(tuple(map(int, elems[8::2])))
322
+ point2D_idxs = np.array(tuple(map(int, elems[9::2])))
323
+ points3D[point3D_id] = Point3D(
324
+ id=point3D_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2D_idxs=point2D_idxs
325
+ )
326
+ return points3D
327
+
328
+
329
+ def read_points3D_binary(path_to_model_file):
330
+ """
331
+ see: src/base/reconstruction.cc
332
+ void Reconstruction::ReadPoints3DBinary(const std::string& path)
333
+ void Reconstruction::WritePoints3DBinary(const std::string& path)
334
+ """
335
+ points3D = {}
336
+ with open(path_to_model_file, "rb") as fid:
337
+ num_points = read_next_bytes(fid, 8, "Q")[0]
338
+ for _ in range(num_points):
339
+ binary_point_line_properties = read_next_bytes(fid, num_bytes=43, format_char_sequence="QdddBBBd")
340
+ point3D_id = binary_point_line_properties[0]
341
+ xyz = np.array(binary_point_line_properties[1:4])
342
+ rgb = np.array(binary_point_line_properties[4:7])
343
+ error = np.array(binary_point_line_properties[7])
344
+ track_length = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
345
+ track_elems = read_next_bytes(fid, num_bytes=8 * track_length, format_char_sequence="ii" * track_length)
346
+ image_ids = np.array(tuple(map(int, track_elems[0::2])))
347
+ point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))
348
+ points3D[point3D_id] = Point3D(
349
+ id=point3D_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2D_idxs=point2D_idxs
350
+ )
351
+ return points3D
352
+
353
+
354
+ def write_points3D_text(points3D, path):
355
+ """
356
+ see: src/base/reconstruction.cc
357
+ void Reconstruction::ReadPoints3DText(const std::string& path)
358
+ void Reconstruction::WritePoints3DText(const std::string& path)
359
+ """
360
+ if len(points3D) == 0:
361
+ mean_track_length = 0
362
+ else:
363
+ mean_track_length = sum((len(pt.image_ids) for _, pt in points3D.items())) / len(points3D)
364
+ HEADER = (
365
+ "# 3D point list with one line of data per point:\n"
366
+ + "# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n"
367
+ + "# Number of points: {}, mean track length: {}\n".format(len(points3D), mean_track_length)
368
+ )
369
+
370
+ with open(path, "w") as fid:
371
+ fid.write(HEADER)
372
+ for _, pt in points3D.items():
373
+ point_header = [pt.id, *pt.xyz, *pt.rgb, pt.error]
374
+ fid.write(" ".join(map(str, point_header)) + " ")
375
+ track_strings = []
376
+ for image_id, point2D in zip(pt.image_ids, pt.point2D_idxs):
377
+ track_strings.append(" ".join(map(str, [image_id, point2D])))
378
+ fid.write(" ".join(track_strings) + "\n")
379
+
380
+
381
+ def write_points3D_binary(points3D, path_to_model_file):
382
+ """
383
+ see: src/base/reconstruction.cc
384
+ void Reconstruction::ReadPoints3DBinary(const std::string& path)
385
+ void Reconstruction::WritePoints3DBinary(const std::string& path)
386
+ """
387
+ with open(path_to_model_file, "wb") as fid:
388
+ write_next_bytes(fid, len(points3D), "Q")
389
+ for _, pt in points3D.items():
390
+ write_next_bytes(fid, pt.id, "Q")
391
+ write_next_bytes(fid, pt.xyz.tolist(), "ddd")
392
+ write_next_bytes(fid, pt.rgb.tolist(), "BBB")
393
+ write_next_bytes(fid, pt.error, "d")
394
+ track_length = pt.image_ids.shape[0]
395
+ write_next_bytes(fid, track_length, "Q")
396
+ for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs):
397
+ write_next_bytes(fid, [image_id, point2D_id], "ii")
398
+
399
+
400
+ def detect_model_format(path, ext):
401
+ if (
402
+ os.path.isfile(os.path.join(path, "cameras" + ext))
403
+ and os.path.isfile(os.path.join(path, "images" + ext))
404
+ and os.path.isfile(os.path.join(path, "points3D" + ext))
405
+ ):
406
+ print("Detected model format: '" + ext + "'")
407
+ return True
408
+
409
+ return False
410
+
411
+
412
+ def read_model(path, ext=""):
413
+ # try to detect the extension automatically
414
+ if ext == "":
415
+ if detect_model_format(path, ".bin"):
416
+ ext = ".bin"
417
+ elif detect_model_format(path, ".txt"):
418
+ ext = ".txt"
419
+ else:
420
+ print("Provide model format: '.bin' or '.txt'")
421
+ return
422
+
423
+ if ext == ".txt":
424
+ cameras = read_cameras_text(os.path.join(path, "cameras" + ext))
425
+ images = read_images_text(os.path.join(path, "images" + ext))
426
+ points3D = read_points3D_text(os.path.join(path, "points3D") + ext)
427
+ else:
428
+ cameras = read_cameras_binary(os.path.join(path, "cameras" + ext))
429
+ images = read_images_binary(os.path.join(path, "images" + ext))
430
+ points3D = read_points3D_binary(os.path.join(path, "points3D") + ext)
431
+ return cameras, images, points3D
432
+
433
+
434
+ def write_model(cameras, images, points3D, path, ext=".bin"):
435
+ if ext == ".txt":
436
+ write_cameras_text(cameras, os.path.join(path, "cameras" + ext))
437
+ write_images_text(images, os.path.join(path, "images" + ext))
438
+ write_points3D_text(points3D, os.path.join(path, "points3D") + ext)
439
+ else:
440
+ write_cameras_binary(cameras, os.path.join(path, "cameras" + ext))
441
+ write_images_binary(images, os.path.join(path, "images" + ext))
442
+ write_points3D_binary(points3D, os.path.join(path, "points3D") + ext)
443
+ return cameras, images, points3D
444
+
445
+
446
+ def qvec2rotmat(qvec):
447
+ return np.array(
448
+ [
449
+ [
450
+ 1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
451
+ 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
452
+ 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],
453
+ ],
454
+ [
455
+ 2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
456
+ 1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
457
+ 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],
458
+ ],
459
+ [
460
+ 2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
461
+ 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
462
+ 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,
463
+ ],
464
+ ]
465
+ )
466
+
467
+
468
+ def rotmat2qvec(R):
469
+ Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
470
+ K = (
471
+ np.array(
472
+ [
473
+ [Rxx - Ryy - Rzz, 0, 0, 0],
474
+ [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
475
+ [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
476
+ [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz],
477
+ ]
478
+ )
479
+ / 3.0
480
+ )
481
+ eigvals, eigvecs = np.linalg.eigh(K)
482
+ qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
483
+ if qvec[0] < 0:
484
+ qvec *= -1
485
+ return qvec
486
+
487
+
488
+ def main():
489
+ parser = argparse.ArgumentParser(description="Read and write COLMAP binary and text models")
490
+ parser.add_argument("--input_model", help="path to input model folder")
491
+ parser.add_argument("--input_format", choices=[".bin", ".txt"], help="input model format", default="")
492
+ parser.add_argument("--output_model", help="path to output model folder")
493
+ parser.add_argument("--output_format", choices=[".bin", ".txt"], help="outut model format", default=".txt")
494
+ args = parser.parse_args()
495
+
496
+ cameras, images, points3D = read_model(path=args.input_model, ext=args.input_format)
497
+
498
+ print("num_cameras:", len(cameras))
499
+ print("num_images:", len(images))
500
+ print("num_points3D:", len(points3D))
501
+
502
+ if args.output_model is not None:
503
+ write_model(cameras, images, points3D, path=args.output_model, ext=args.output_format)
504
+
505
+
506
+ if __name__ == "__main__":
507
+ main()
utils/reflectance.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Different Reflectance function definition.
2
+
3
+ Author: Travis Driver
4
+ """
5
+ import numpy as np
6
+
7
+ from typing import Tuple
8
+
9
+
10
+ def lunar_lambert_reflectance(
11
+ R_CB: np.ndarray, r_BC_C: np.ndarray, l_B: np.ndarray, s_C: np.ndarray, n_B: np.ndarray
12
+ ) -> Tuple[float, float, float, float]:
13
+ s_B = (R_CB.T @ s_C.reshape((3, -1))).flatten()
14
+ r_B = (-R_CB.T @ r_BC_C.reshape((3, -1))).flatten()
15
+ e_B = r_B - l_B
16
+ e_B /= np.linalg.norm(e_B)
17
+ cs = np.sum(s_B * n_B)
18
+ ce = np.sum(e_B * n_B)
19
+ phi = np.arccos(np.sum(s_B * e_B))
20
+ L = np.exp(-np.rad2deg(phi) / 60.0)
21
+ reflect = (1 - L) * cs + L * 2.0 * cs / (cs + ce)
22
+
23
+ return reflect, np.arccos(cs), np.arccos(ce), phi
24
+
25
+
26
+ def schroder2013_reflectance(
27
+ R_CB: np.ndarray, r_BC_C: np.ndarray, l_B: np.ndarray, s_C: np.ndarray, n_B: np.ndarray
28
+ ) -> Tuple[float, float, float, float]:
29
+ s_B = (R_CB.T @ s_C.reshape((3, -1))).flatten()
30
+ r_B = (-R_CB.T @ r_BC_C.reshape((3, -1))).flatten()
31
+ e_B = r_B - l_B
32
+ e_B /= np.linalg.norm(e_B)
33
+ cs = np.sum(s_B * n_B)
34
+ ce = np.sum(e_B * n_B)
35
+ phi = np.arccos(np.sum(s_B * e_B))
36
+
37
+ cp0, cp1 = 0.830, -7.22e-3 * 180 / np.pi
38
+ L = cp0 + cp1 * phi
39
+
40
+ c0, c1, c2, c3, c4 = (
41
+ 0.301,
42
+ -5.17e-3 * 180.0 / np.pi,
43
+ 5.51e-5 * (180.0 / np.pi) ** 2,
44
+ -3.13e-7 * (180.0 / np.pi) ** 3,
45
+ 0.699e-9 * (180.0 / np.pi) ** 4,
46
+ )
47
+ aeq = c0 + c1 * phi + c2 * phi ** 2 + c3 * phi ** 3 + c4 * phi ** 4
48
+
49
+ reflect = aeq * ((1 - L) * cs + L * 2.0 * cs / (cs + ce))
50
+
51
+ return reflect, np.arccos(cs), np.arccos(ce), phi
utils/spc_types.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classes for storing SPC data.
2
+
3
+ Author: Travis Driver
4
+ """
5
+ import os
6
+ from typing import NamedTuple
7
+
8
+ import numpy as np
9
+ import gtsam
10
+
11
+ from utils.read_write_model import (
12
+ rotmat2qvec,
13
+ qvec2rotmat,
14
+ write_cameras_text,
15
+ read_cameras_text,
16
+ detect_model_format,
17
+ )
18
+
19
+
20
+ class SPCImage(NamedTuple):
21
+ """Stores camera extrinsics and Sun vector information."""
22
+
23
+ id: int
24
+ qvec: np.ndarray
25
+ tvec: np.ndarray
26
+ svec: np.ndarray
27
+ camera_id: int
28
+ name: str
29
+ xys: np.ndarray
30
+ intens: np.ndarray
31
+ point3D_ids: np.ndarray
32
+ scale: float
33
+ bias: float
34
+
35
+ def qvec2rotmat(self) -> np.ndarray:
36
+ """Converts quaternion to rotation matrix."""
37
+ return qvec2rotmat(self.qvec)
38
+
39
+ def apply_sim3(self, S_AB: gtsam.Similarity3) -> "SPCImage":
40
+ """Apply Sim(3) transformation to stored pose."""
41
+ T_BC = gtsam.Pose3(gtsam.Rot3(self.qvec2rotmat()), self.tvec).inverse()
42
+ T_CA = S_AB.transformFrom(T_BC).inverse()
43
+ return SPCImage(
44
+ id=self.id,
45
+ qvec=rotmat2qvec(T_CA.rotation().matrix()).flatten(),
46
+ tvec=T_CA.translation().flatten(),
47
+ svec=self.svec,
48
+ camera_id=self.camera_id,
49
+ name=self.name,
50
+ xys=self.xys,
51
+ intens=self.intens,
52
+ point3D_ids=self.point3D_ids,
53
+ scale=self.scale,
54
+ bias=self.bias,
55
+ )
56
+
57
+
58
+ class SPCPoint3D(NamedTuple):
59
+ """Stores surface landmark information."""
60
+
61
+ id: int
62
+ xyz: int
63
+ nvec: np.ndarray
64
+ albedo: float
65
+ rgb: np.ndarray
66
+ error: float
67
+ image_ids: np.ndarray
68
+ point2D_idxs: np.ndarray
69
+
70
+ def apply_sim3(self, S_AB: gtsam.Similarity3) -> "SPCPoint3D":
71
+ """Apply Sim(3) transformation to stored points."""
72
+ return SPCPoint3D(
73
+ id=self.id,
74
+ xyz=S_AB.transformFrom(self.xyz).flatten(),
75
+ nvec=(S_AB.rotation().matrix() @ self.nvec[..., None]).flatten(),
76
+ albedo=self.albedo,
77
+ rgb=self.rgb,
78
+ error=self.error,
79
+ image_ids=self.image_ids,
80
+ point2D_idxs=self.point2D_idxs,
81
+ )
82
+
83
+
84
+ def read_spcimages_text(path):
85
+ """
86
+ see: src/base/reconstruction.cc
87
+ void Reconstruction::ReadImagesText(const std::string& path)
88
+ void Reconstruction::WriteImagesText(const std::string& path)
89
+ """
90
+ images = {}
91
+ with open(path, "r") as fid:
92
+ while True:
93
+ line = fid.readline()
94
+ if not line:
95
+ break
96
+ line = line.strip()
97
+ if len(line) > 0 and line[0] != "#":
98
+ elems = line.split()
99
+ image_id = int(elems[0])
100
+ qvec = np.array(tuple(map(float, elems[1:5])))
101
+ tvec = np.array(tuple(map(float, elems[5:8])))
102
+ svec = np.array(tuple(map(float, elems[8:11])))
103
+ camera_id = int(elems[11])
104
+ image_name = elems[12]
105
+ scale = float(elems[13])
106
+ bias = float(elems[14])
107
+ elems = fid.readline().split()
108
+ xys = np.column_stack([tuple(map(float, elems[0::4])), tuple(map(float, elems[1::4]))])
109
+ intens = np.array(tuple(map(float, elems[2::4])))
110
+ point3D_ids = np.array(tuple(map(int, elems[3::4])))
111
+ images[image_id] = SPCImage(
112
+ id=image_id,
113
+ qvec=qvec,
114
+ tvec=tvec,
115
+ svec=svec,
116
+ camera_id=camera_id,
117
+ name=image_name,
118
+ xys=xys,
119
+ intens=intens,
120
+ point3D_ids=point3D_ids,
121
+ scale=scale,
122
+ bias=bias,
123
+ )
124
+ return images
125
+
126
+
127
+ def write_spcimages_text(images, path):
128
+ """
129
+ see: src/base/reconstruction.cc
130
+ void Reconstruction::ReadImagesText(const std::string& path)
131
+ void Reconstruction::WriteImagesText(const std::string& path)
132
+ """
133
+ # TODO: Add Point3D IDs to Image.
134
+ # if len(images) == 0:
135
+ # mean_observations = 0
136
+ # else:
137
+ # mean_observations = sum((len(img.point3D_ids) for img in images.values())) / len(images)
138
+ HEADER = (
139
+ "# Image list with two lines of data per image:\n"
140
+ + "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, SX, SY, SZ, CAMERA_ID, NAME, SCALE, BIAS\n"
141
+ + "# POINTS2D[] as (X, Y, INTENSITY, POINT3D_ID)\n"
142
+ + "# Number of images: {}, mean observations per image: {}\n".format(len(images), "TBD")
143
+ )
144
+
145
+ with open(path, "w") as fid:
146
+ fid.write(HEADER)
147
+ for _, img in images.items():
148
+ if img.intens is None:
149
+ continue
150
+ image_header = [img.id, *img.qvec, *img.tvec, *img.svec, img.camera_id, img.name, img.scale, img.bias]
151
+ first_line = " ".join(map(str, image_header))
152
+ fid.write(first_line + "\n")
153
+
154
+ points_strings = []
155
+ # for xy, inten, point3D_id in zip(img.xys, img.intens, img.point3D_ids):
156
+ for xy, inten, p3d_id in zip(img.xys, img.intens, img.point3D_ids):
157
+ points_strings.append(" ".join(map(str, [*xy, inten, p3d_id])))
158
+ fid.write(" ".join(points_strings) + "\n")
159
+
160
+
161
+ def read_spcpoints3D_text(path):
162
+ """
163
+ see: src/base/reconstruction.cc
164
+ void Reconstruction::ReadPoints3DText(const std::string& path)
165
+ void Reconstruction::WritePoints3DText(const std::string& path)
166
+ """
167
+ points3D = {}
168
+ with open(path, "r") as fid:
169
+ while True:
170
+ line = fid.readline()
171
+ if not line:
172
+ break
173
+ line = line.strip()
174
+ if len(line) > 0 and line[0] != "#":
175
+ elems = line.split()
176
+ point3D_id = int(elems[0])
177
+ xyz = np.array(tuple(map(float, elems[1:4])))
178
+ nvec = np.array(tuple(map(float, elems[4:7])))
179
+ albedo = float(elems[7])
180
+ rgb = np.array(tuple(map(int, elems[8:11])))
181
+ error = float(elems[11])
182
+ image_ids = np.array(tuple(map(int, elems[12::2])))
183
+ point2D_idxs = np.array(tuple(map(int, elems[13::2])))
184
+ points3D[point3D_id] = SPCPoint3D(
185
+ id=point3D_id,
186
+ xyz=xyz,
187
+ nvec=nvec,
188
+ albedo=albedo,
189
+ rgb=rgb,
190
+ error=error,
191
+ image_ids=image_ids,
192
+ point2D_idxs=point2D_idxs,
193
+ )
194
+ return points3D
195
+
196
+
197
+ def write_spcpoints3D_text(points3D, path):
198
+ """
199
+ see: src/base/reconstruction.cc
200
+ void Reconstruction::ReadPoints3DText(const std::string& path)
201
+ void Reconstruction::WritePoints3DText(const std::string& path)
202
+ """
203
+ if len(points3D) == 0:
204
+ mean_track_length = 0
205
+ else:
206
+ mean_track_length = sum((len(pt.image_ids) for _, pt in points3D.items())) / len(points3D)
207
+ HEADER = (
208
+ "# 3D point list with one line of data per point:\n"
209
+ + "# POINT3D_ID, X, Y, Z, NX, NY, NZ, ALBEDO, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n"
210
+ + "# Number of points: {}, mean track length: {}\n".format(len(points3D), mean_track_length)
211
+ )
212
+
213
+ with open(path, "w") as fid:
214
+ fid.write(HEADER)
215
+ for _, pt in points3D.items():
216
+ if pt.albedo is None:
217
+ continue
218
+ point_header = [pt.id, *pt.xyz, *pt.nvec, pt.albedo, *pt.rgb.astype(int), pt.error]
219
+ fid.write(" ".join(map(str, point_header)) + " ")
220
+ track_strings = []
221
+ for image_id, point2D in zip(pt.image_ids, pt.point2D_idxs):
222
+ track_strings.append(" ".join(map(str, [image_id, point2D])))
223
+ fid.write(" ".join(track_strings) + "\n")
224
+
225
+
226
+ def read_spc_model(path, ext=""):
227
+ # try to detect the extension automatically
228
+ if ext == "":
229
+ if detect_model_format(path, ".bin"):
230
+ ext = ".bin"
231
+ elif detect_model_format(path, ".txt"):
232
+ ext = ".txt"
233
+ else:
234
+ print("Provide model format: '.bin' or '.txt'")
235
+ return
236
+
237
+ if ext == ".txt":
238
+ cameras = read_cameras_text(os.path.join(path, "cameras" + ext))
239
+ images = read_spcimages_text(os.path.join(path, "images" + ext))
240
+ points3D = read_spcpoints3D_text(os.path.join(path, "points3D") + ext)
241
+ else:
242
+ raise RuntimeError("Support for binary files not supported.")
243
+ return cameras, images, points3D
244
+
245
+
246
+ def write_spc_model(cameras, images, points3D, path, ext=".txt"):
247
+ if ext == ".txt":
248
+ write_cameras_text(cameras, os.path.join(path, "cameras" + ext))
249
+ write_spcimages_text(images, os.path.join(path, "images" + ext))
250
+ write_spcpoints3D_text(points3D, os.path.join(path, "points3D") + ext)
251
+ else:
252
+ raise RuntimeError("Support for binary files not supported.")
253
+ return cameras, images, points3D