colmap_loader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #
  2. # Copyright (C) 2023, Inria
  3. # GRAPHDECO research group, https://team.inria.fr/graphdeco
  4. # All rights reserved.
  5. #
  6. # This software is free for non-commercial, research and evaluation use
  7. # under the terms of the LICENSE.md file.
  8. #
  9. # For inquiries contact george.drettakis@inria.fr
  10. #
  11. import numpy as np
  12. import collections
  13. import struct
  14. CameraModel = collections.namedtuple(
  15. "CameraModel", ["model_id", "model_name", "num_params"])
  16. Camera = collections.namedtuple(
  17. "Camera", ["id", "model", "width", "height", "params"])
  18. BaseImage = collections.namedtuple(
  19. "Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
  20. Point3D = collections.namedtuple(
  21. "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
  22. CAMERA_MODELS = {
  23. CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
  24. CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
  25. CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
  26. CameraModel(model_id=3, model_name="RADIAL", num_params=5),
  27. CameraModel(model_id=4, model_name="OPENCV", num_params=8),
  28. CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
  29. CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
  30. CameraModel(model_id=7, model_name="FOV", num_params=5),
  31. CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
  32. CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
  33. CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12)
  34. }
  35. CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)
  36. for camera_model in CAMERA_MODELS])
  37. CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)
  38. for camera_model in CAMERA_MODELS])
  39. def qvec2rotmat(qvec):
  40. return np.array([
  41. [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
  42. 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
  43. 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
  44. [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
  45. 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
  46. 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
  47. [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
  48. 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
  49. 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
  50. def rotmat2qvec(R):
  51. Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
  52. K = np.array([
  53. [Rxx - Ryy - Rzz, 0, 0, 0],
  54. [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
  55. [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
  56. [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
  57. eigvals, eigvecs = np.linalg.eigh(K)
  58. qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
  59. if qvec[0] < 0:
  60. qvec *= -1
  61. return qvec
  62. class Image(BaseImage):
  63. def qvec2rotmat(self):
  64. return qvec2rotmat(self.qvec)
  65. def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
  66. """Read and unpack the next bytes from a binary file.
  67. :param fid:
  68. :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
  69. :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
  70. :param endian_character: Any of {@, =, <, >, !}
  71. :return: Tuple of read and unpacked values.
  72. """
  73. data = fid.read(num_bytes)
  74. return struct.unpack(endian_character + format_char_sequence, data)
  75. def read_points3D_text(path):
  76. """
  77. see: src/base/reconstruction.cc
  78. void Reconstruction::ReadPoints3DText(const std::string& path)
  79. void Reconstruction::WritePoints3DText(const std::string& path)
  80. """
  81. xyzs = None
  82. rgbs = None
  83. errors = None
  84. with open(path, "r") as fid:
  85. while True:
  86. line = fid.readline()
  87. if not line:
  88. break
  89. line = line.strip()
  90. if len(line) > 0 and line[0] != "#":
  91. elems = line.split()
  92. xyz = np.array(tuple(map(float, elems[1:4])))
  93. rgb = np.array(tuple(map(int, elems[4:7])))
  94. error = np.array(float(elems[7]))
  95. if xyzs is None:
  96. xyzs = xyz[None, ...]
  97. rgbs = rgb[None, ...]
  98. errors = error[None, ...]
  99. else:
  100. xyzs = np.append(xyzs, xyz[None, ...], axis=0)
  101. rgbs = np.append(rgbs, rgb[None, ...], axis=0)
  102. errors = np.append(errors, error[None, ...], axis=0)
  103. return xyzs, rgbs, errors
  104. def read_points3D_binary(path_to_model_file):
  105. """
  106. see: src/base/reconstruction.cc
  107. void Reconstruction::ReadPoints3DBinary(const std::string& path)
  108. void Reconstruction::WritePoints3DBinary(const std::string& path)
  109. """
  110. with open(path_to_model_file, "rb") as fid:
  111. num_points = read_next_bytes(fid, 8, "Q")[0]
  112. xyzs = np.empty((num_points, 3))
  113. rgbs = np.empty((num_points, 3))
  114. errors = np.empty((num_points, 1))
  115. for p_id in range(num_points):
  116. binary_point_line_properties = read_next_bytes(
  117. fid, num_bytes=43, format_char_sequence="QdddBBBd")
  118. xyz = np.array(binary_point_line_properties[1:4])
  119. rgb = np.array(binary_point_line_properties[4:7])
  120. error = np.array(binary_point_line_properties[7])
  121. track_length = read_next_bytes(
  122. fid, num_bytes=8, format_char_sequence="Q")[0]
  123. track_elems = read_next_bytes(
  124. fid, num_bytes=8*track_length,
  125. format_char_sequence="ii"*track_length)
  126. xyzs[p_id] = xyz
  127. rgbs[p_id] = rgb
  128. errors[p_id] = error
  129. return xyzs, rgbs, errors
  130. def read_intrinsics_text(path):
  131. """
  132. Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py
  133. """
  134. cameras = {}
  135. with open(path, "r") as fid:
  136. while True:
  137. line = fid.readline()
  138. if not line:
  139. break
  140. line = line.strip()
  141. if len(line) > 0 and line[0] != "#":
  142. elems = line.split()
  143. camera_id = int(elems[0])
  144. model = elems[1]
  145. assert model == "PINHOLE", "While the loader support other types, the rest of the code assumes PINHOLE"
  146. width = int(elems[2])
  147. height = int(elems[3])
  148. params = np.array(tuple(map(float, elems[4:])))
  149. cameras[camera_id] = Camera(id=camera_id, model=model,
  150. width=width, height=height,
  151. params=params)
  152. return cameras
  153. def read_extrinsics_binary(path_to_model_file):
  154. """
  155. see: src/base/reconstruction.cc
  156. void Reconstruction::ReadImagesBinary(const std::string& path)
  157. void Reconstruction::WriteImagesBinary(const std::string& path)
  158. """
  159. images = {}
  160. with open(path_to_model_file, "rb") as fid:
  161. num_reg_images = read_next_bytes(fid, 8, "Q")[0]
  162. for _ in range(num_reg_images):
  163. binary_image_properties = read_next_bytes(
  164. fid, num_bytes=64, format_char_sequence="idddddddi")
  165. image_id = binary_image_properties[0]
  166. qvec = np.array(binary_image_properties[1:5])
  167. tvec = np.array(binary_image_properties[5:8])
  168. camera_id = binary_image_properties[8]
  169. image_name = ""
  170. current_char = read_next_bytes(fid, 1, "c")[0]
  171. while current_char != b"\x00": # look for the ASCII 0 entry
  172. image_name += current_char.decode("utf-8")
  173. current_char = read_next_bytes(fid, 1, "c")[0]
  174. num_points2D = read_next_bytes(fid, num_bytes=8,
  175. format_char_sequence="Q")[0]
  176. x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,
  177. format_char_sequence="ddq"*num_points2D)
  178. xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),
  179. tuple(map(float, x_y_id_s[1::3]))])
  180. point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
  181. images[image_id] = Image(
  182. id=image_id, qvec=qvec, tvec=tvec,
  183. camera_id=camera_id, name=image_name,
  184. xys=xys, point3D_ids=point3D_ids)
  185. return images
  186. def read_intrinsics_binary(path_to_model_file):
  187. """
  188. see: src/base/reconstruction.cc
  189. void Reconstruction::WriteCamerasBinary(const std::string& path)
  190. void Reconstruction::ReadCamerasBinary(const std::string& path)
  191. """
  192. cameras = {}
  193. with open(path_to_model_file, "rb") as fid:
  194. num_cameras = read_next_bytes(fid, 8, "Q")[0]
  195. for _ in range(num_cameras):
  196. camera_properties = read_next_bytes(
  197. fid, num_bytes=24, format_char_sequence="iiQQ")
  198. camera_id = camera_properties[0]
  199. model_id = camera_properties[1]
  200. model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
  201. width = camera_properties[2]
  202. height = camera_properties[3]
  203. num_params = CAMERA_MODEL_IDS[model_id].num_params
  204. params = read_next_bytes(fid, num_bytes=8*num_params,
  205. format_char_sequence="d"*num_params)
  206. cameras[camera_id] = Camera(id=camera_id,
  207. model=model_name,
  208. width=width,
  209. height=height,
  210. params=np.array(params))
  211. assert len(cameras) == num_cameras
  212. return cameras
  213. def read_extrinsics_text(path):
  214. """
  215. Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py
  216. """
  217. images = {}
  218. with open(path, "r") as fid:
  219. while True:
  220. line = fid.readline()
  221. if not line:
  222. break
  223. line = line.strip()
  224. if len(line) > 0 and line[0] != "#":
  225. elems = line.split()
  226. image_id = int(elems[0])
  227. qvec = np.array(tuple(map(float, elems[1:5])))
  228. tvec = np.array(tuple(map(float, elems[5:8])))
  229. camera_id = int(elems[8])
  230. image_name = elems[9]
  231. elems = fid.readline().split()
  232. xys = np.column_stack([tuple(map(float, elems[0::3])),
  233. tuple(map(float, elems[1::3]))])
  234. point3D_ids = np.array(tuple(map(int, elems[2::3])))
  235. images[image_id] = Image(
  236. id=image_id, qvec=qvec, tvec=tvec,
  237. camera_id=camera_id, name=image_name,
  238. xys=xys, point3D_ids=point3D_ids)
  239. return images
  240. def read_colmap_bin_array(path):
  241. """
  242. Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py
  243. :param path: path to the colmap binary file.
  244. :return: nd array with the floating point values in the value
  245. """
  246. with open(path, "rb") as fid:
  247. width, height, channels = np.genfromtxt(fid, delimiter="&", max_rows=1,
  248. usecols=(0, 1, 2), dtype=int)
  249. fid.seek(0)
  250. num_delimiter = 0
  251. byte = fid.read(1)
  252. while True:
  253. if byte == b"&":
  254. num_delimiter += 1
  255. if num_delimiter >= 3:
  256. break
  257. byte = fid.read(1)
  258. array = np.fromfile(fid, np.float32)
  259. array = array.reshape((width, height, channels), order="F")
  260. return np.transpose(array, (1, 0, 2)).squeeze()