colmap_loader.py 11 KB

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