当前位置:   article > 正文

基于深度学习的三维重建(一):三维重建简介、patchmatchNet环境部署、用colmap如何测试自己的数据集

基于深度学习的三维重建

目录

1.什么是三维重建

2.MVS是什么

3.传统MVS的局限性和为什么基于深度学习的MVS性能好于传统三维重建

4.基础概念

5. patchmatchNet环境配置

6.如何测试自己的数据集(位姿计算)

6.1 colmap导出位姿

6.2 将colmap位姿转换成MVS读取的数据格式


1.什么是三维重建

        用相机拍摄真实世界的物体、场景,并通过计算机视觉技术进行处理,从而得到物体的三维模型。英文术语:3D Reconstruction。
        涉及的主要技术有:多视图立体几何、深度图估计、点云处理、网格重建和优化、纹理贴图、马尔科夫随机场、图割等。
        是增强现实(AR)、混合现实(MR)、机器人导航、自动驾驶等领域的核心技术之一。

2.MVS是什么

        用RGB-D信息重建3D几何的模型,输入的话是一系列的RGB-D照片,这些照片会有一些重合部分,我们计算这些照片的位姿信息(每个拍摄的相机角度的位置),我们就知道了每帧间的位置关系,然后对它进行一个3D模型的重建,最后将材质信息给它贴上去(纹理贴图,将RGB-D信息贴到几何模型上)。

        这里的位姿信息获得是通过SLAM或者SFM来做的,我们就可以得到它的深度图进行点云融合等操作。

3.传统MVS的局限性和为什么基于深度学习的MVS性能好于传统三维重建

        MVS重建我们是基于RGB-D信息做的,也就是说我们恢复3D信息是通过立体匹配等方法进行深度恢复,如果RGB信息出现大面积的单色情况(如下图)没有纹理信息的或者是透明的重复纹理的,那么我们很难进行特征点匹配,也就没有办法通过立体匹配进行深度恢复了,最终导致失败。

        在深度学习中,我们通过大量的数据学习一些信息规律和信息。

        但其也有一定的缺点,比如依赖显存和内存,依赖大数据,难以重建高分辨率的模型。

4.基础概念

        ①深度图(depth)/视差图(disparity)

        a.深度图:场景中每个点到相机的距离
        b.视差图:同一个场景在两个相机下成像的像素的位置偏差dis
        c.两者关系: depth = \frac{b_f}{dis},是三维信息的一种表示方式。

        深度图存储的就是相机坐标系下的Z

        ②三维点云:

        a.三维点云是某个坐标系下的点的数据集。
        b.包含了丰富的信息,包括三维坐标XYZ、颜色RGB等信息。

        ③三维网格:

        由物体的邻接点云构成的多边形组成的,通常由三角形、四边形或者其它的简单凸多边形组成。

       ④纹理贴图模型:

        带有颜色信息的三维网格模型。
        所有的颜色信息存储在一张纹理图上,显示时根据每个网格的纹理坐标和对应的纹理图进行渲染得到高分辨率的彩色模型。

        ⑤相机模型:

5. patchmatchNet环境配置

        利用Anaconda配置虚拟环境,python版本为3.8。如果有GPU的话cuda推荐版本为11.3,我是3080显卡,安装的cuda版本为11.3,pytorch版本为1.11.0,可顺利跑通!

         下载patchmatchNet源码:

PatchNet Git地址https://github.com/FangjinhuaWang/PatchmatchNet

        里面有个requirements.txt

        一键安装:pip install -r requirements.txt

        到这里我们就安装成功了,测试一下:

        先0下载数据集:

        下载DTU数据集 dtu.zip,在项目文件夹新建data文件夹,解压到data文件夹中。

        在代码路径下打开终端,激活conda环境,运行eval.sh,如果没有gpu,运行eval_cpu.sh。

        运行结果保存在当前目录下./outputs下。

        如果显卡性能不好或者CPU跑性能过慢的话,我们可以改变默认的分辨率大小,在eval.py中,main函数中,img_wh = (800,600),可以改为原来的一半。同时也要改dataset/dtu_yao_eval.py文件,MvsDataset类中更改图像分辨率。

        最终重建的结果如下,效果还是不错滴!

6.如何测试自己的数据集(位姿计算)

6.1 colmap导出位姿

        比如我们用手机拍摄了一组照片,要对其进行三维重建,应该怎么做呢?

        我们上面说到,输入到patchmatchNet网络中的参数是一组照片以及它们的深度信息(位姿+深度范围或者稀疏点云),因此我们主要做的就是数据格式的转换。

        第一步就是位姿的计算,无论是sfm或者SLAM除了输出位姿(R,t)以外都会有稀疏点的输出,并且告诉哪些稀疏点会被哪些相机和关键帧看到,我们就是用这些信息完成重建。

        一、数据:

        数据要求:图的质量要好不能模糊遮挡、帧之间要有大量的重合区域。(弱纹理,高反光效果不好)

        二、位姿计算:使用colmap计算位姿,也可以使用别的比如OpenMVG,Slam这些需要自己写转换脚本参考colmap_input.py。colmap git链接https://github.com/colmap/colmap/releases        在windows下的使用,下载这两个其中一个,

        双击:

        新建一个工程:

        Database是新建的数据库名称,Images是包含图片的文件夹。

        可以看到桌面已经有这个工程了。

        下一步就是特征提取,

        点击提取

        特征匹配完成!

        重建,点击开始重建。

        红色的就是每帧相机的位置,黑色的就是稀疏的地图点。

        现在我们就得到了哪些相机可以观测到哪些点、相机的位姿信息、相机的内参等。

        我们就可以用地图点计算深度范围计算初始的深度图都是可以的,接下来我们导出信息。FIle/Import model as text:

        camera.txt里面是相机的参数:对应相机ID、相机属性、图像大小、相机内参

        images.txt:图像ID、平移四元数、旋转信息、哪个相机照的这个图像、图像的名称

         POINTS2D[] as (X, Y, POINT3D_ID):投影坐标

        points3D.txt:3D点的ID、3D点坐标、3D点的RGB信息、错误信息、可以被哪张图片看到,该点在该张图片的索引是多少。

6.2 将colmap位姿转换成MVS读取的数据格式

        转换成MVS格式直接由DataLoader调用即可:

        我们看怎么实现:colmap_input.py 我在源码中进行了标注

  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import collections
  4. import struct
  5. import numpy as np
  6. import multiprocessing as mp
  7. import os
  8. import argparse
  9. import shutil
  10. import cv2
  11. #============================ read_model.py ============================#
  12. CameraModel = collections.namedtuple(
  13. "CameraModel", ["model_id", "model_name", "num_params"])
  14. Camera = collections.namedtuple(
  15. "Camera", ["id", "model", "width", "height", "params"])
  16. BaseImage = collections.namedtuple(
  17. "Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
  18. Point3D = collections.namedtuple(
  19. "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
  20. class Image(BaseImage):
  21. def qvec2rotmat(self):
  22. return qvec2rotmat(self.qvec)
  23. CAMERA_MODELS = {
  24. CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
  25. CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
  26. CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
  27. CameraModel(model_id=3, model_name="RADIAL", num_params=5),
  28. CameraModel(model_id=4, model_name="OPENCV", num_params=8),
  29. CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
  30. CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
  31. CameraModel(model_id=7, model_name="FOV", num_params=5),
  32. CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
  33. CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
  34. CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12)
  35. }
  36. CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model) \
  37. for camera_model in CAMERA_MODELS])
  38. def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
  39. """Read and unpack the next bytes from a binary file.
  40. :param fid:
  41. :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
  42. :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
  43. :param endian_character: Any of {@, =, <, >, !}
  44. :return: Tuple of read and unpacked values.
  45. """
  46. data = fid.read(num_bytes)
  47. return struct.unpack(endian_character + format_char_sequence, data)
  48. def read_cameras_text(path):
  49. """
  50. see: src/base/reconstruction.cc
  51. void Reconstruction::WriteCamerasText(const std::string& path)
  52. void Reconstruction::ReadCamerasText(const std::string& path)
  53. """
  54. cameras = {}
  55. with open(path, "r") as fid:
  56. while True:
  57. line = fid.readline()
  58. if not line:
  59. break
  60. line = line.strip()
  61. if len(line) > 0 and line[0] != "#":
  62. elems = line.split()
  63. camera_id = int(elems[0])
  64. # camera 类型
  65. model = elems[1]
  66. width = int(elems[2])
  67. height = int(elems[3])
  68. # 相机的参数
  69. params = np.array(tuple(map(float, elems[4:])))
  70. cameras[camera_id] = Camera(id=camera_id, model=model,
  71. width=width, height=height,
  72. params=params)
  73. return cameras
  74. def read_cameras_binary(path_to_model_file):
  75. """
  76. see: src/base/reconstruction.cc
  77. void Reconstruction::WriteCamerasBinary(const std::string& path)
  78. void Reconstruction::ReadCamerasBinary(const std::string& path)
  79. """
  80. cameras = {}
  81. with open(path_to_model_file, "rb") as fid:
  82. num_cameras = read_next_bytes(fid, 8, "Q")[0]
  83. print("num of cameras")
  84. print(num_cameras)
  85. for camera_line_index in range(num_cameras):
  86. camera_properties = read_next_bytes(
  87. fid, num_bytes=24, format_char_sequence="iiQQ")
  88. camera_id = camera_properties[0]
  89. print("camera id")
  90. print(camera_id)
  91. model_id = camera_properties[1]
  92. # print("model id")
  93. # print(model_id)
  94. model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
  95. width = camera_properties[2]
  96. height = camera_properties[3]
  97. num_params = CAMERA_MODEL_IDS[model_id].num_params
  98. params = read_next_bytes(fid, num_bytes=8*num_params,
  99. format_char_sequence="d"*num_params)
  100. cameras[camera_id] = Camera(id=camera_id,
  101. model=model_name,
  102. width=width,
  103. height=height,
  104. params=np.array(params))
  105. assert len(cameras) == num_cameras
  106. return cameras
  107. def read_images_text(path):
  108. """
  109. see: src/base/reconstruction.cc
  110. void Reconstruction::ReadImagesText(const std::string& path)
  111. void Reconstruction::WriteImagesText(const std::string& path)
  112. """
  113. images = {}
  114. with open(path, "r") as fid:
  115. while True:
  116. # 一行一行读
  117. line = fid.readline()
  118. if not line:
  119. break
  120. line = line.strip()
  121. # 前面几行有带#的注释
  122. if len(line) > 0 and line[0] != "#":
  123. elems = line.split()
  124. image_id = int(elems[0])
  125. # 四元数(旋转矩阵转换的四元数)
  126. qvec = np.array(tuple(map(float, elems[1:5])))
  127. # 内参t
  128. tvec = np.array(tuple(map(float, elems[5:8])))
  129. # camera ID
  130. camera_id = int(elems[8])
  131. # 图片名称
  132. image_name = elems[9]
  133. elems = fid.readline().split()
  134. # 特征点在图像中的2D坐标
  135. xys = np.column_stack([tuple(map(float, elems[0::3])),
  136. tuple(map(float, elems[1::3]))])
  137. point3D_ids = np.array(tuple(map(int, elems[2::3])))
  138. images[image_id] = Image(
  139. id=image_id, qvec=qvec, tvec=tvec,
  140. camera_id=camera_id, name=image_name,
  141. xys=xys, point3D_ids=point3D_ids)
  142. return images
  143. def read_images_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. # print("img num")
  153. # print(num_reg_images)
  154. for image_index in range(num_reg_images):
  155. binary_image_properties = read_next_bytes(
  156. fid, num_bytes=64, format_char_sequence="idddddddi")
  157. image_id = binary_image_properties[0]
  158. # print("image_id")
  159. # print(image_id)
  160. qvec = np.array(binary_image_properties[1:5])
  161. tvec = np.array(binary_image_properties[5:8])
  162. camera_id = binary_image_properties[8]
  163. # print("image_id_camera")
  164. # print(camera_id)
  165. image_name = ""
  166. current_char = read_next_bytes(fid, 1, "c")[0]
  167. while current_char != b"\x00": # look for the ASCII 0 entry
  168. image_name += current_char.decode("utf-8")
  169. current_char = read_next_bytes(fid, 1, "c")[0]
  170. num_points2D = read_next_bytes(fid, num_bytes=8,
  171. format_char_sequence="Q")[0]
  172. x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,
  173. format_char_sequence="ddq"*num_points2D)
  174. xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),
  175. tuple(map(float, x_y_id_s[1::3]))])
  176. point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
  177. # print("point_3d")
  178. # print(point3D_ids)
  179. images[image_id] = Image(
  180. id=image_id, qvec=qvec, tvec=tvec,
  181. camera_id=camera_id, name=image_name,
  182. xys=xys, point3D_ids=point3D_ids)
  183. return images
  184. def read_points3D_text(path):
  185. """
  186. see: src/base/reconstruction.cc
  187. void Reconstruction::ReadPoints3DText(const std::string& path)
  188. void Reconstruction::WritePoints3DText(const std::string& path)
  189. """
  190. points3D = {}
  191. with open(path, "r") as fid:
  192. while True:
  193. line = fid.readline()
  194. if not line:
  195. break
  196. line = line.strip()
  197. if len(line) > 0 and line[0] != "#":
  198. elems = line.split()
  199. point3D_id = int(elems[0])
  200. xyz = np.array(tuple(map(float, elems[1:4])))
  201. rgb = np.array(tuple(map(int, elems[4:7])))
  202. error = float(elems[7])
  203. image_ids = np.array(tuple(map(int, elems[8::2])))
  204. point2D_idxs = np.array(tuple(map(int, elems[9::2])))
  205. points3D[point3D_id] = Point3D(id=point3D_id, xyz=xyz, rgb=rgb,
  206. error=error, image_ids=image_ids,
  207. point2D_idxs=point2D_idxs)
  208. return points3D
  209. def read_points3d_binary(path_to_model_file):
  210. """
  211. see: src/base/reconstruction.cc
  212. void Reconstruction::ReadPoints3DBinary(const std::string& path)
  213. void Reconstruction::WritePoints3DBinary(const std::string& path)
  214. """
  215. points3D = {}
  216. with open(path_to_model_file, "rb") as fid:
  217. num_points = read_next_bytes(fid, 8, "Q")[0]
  218. # print("num points")
  219. # print(num_points)
  220. for point_line_index in range(num_points):
  221. binary_point_line_properties = read_next_bytes(
  222. fid, num_bytes=43, format_char_sequence="QdddBBBd")
  223. point3D_id = binary_point_line_properties[0]
  224. xyz = np.array(binary_point_line_properties[1:4])
  225. rgb = np.array(binary_point_line_properties[4:7])
  226. error = np.array(binary_point_line_properties[7])
  227. track_length = read_next_bytes(
  228. fid, num_bytes=8, format_char_sequence="Q")[0]
  229. track_elems = read_next_bytes(
  230. fid, num_bytes=8*track_length,
  231. format_char_sequence="ii"*track_length)
  232. image_ids = np.array(tuple(map(int, track_elems[0::2])))
  233. point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))
  234. points3D[point3D_id] = Point3D(
  235. id=point3D_id, xyz=xyz, rgb=rgb,
  236. error=error, image_ids=image_ids,
  237. point2D_idxs=point2D_idxs)
  238. return points3D
  239. def read_model(path, ext):
  240. if ext == ".txt":
  241. # 读取相机参数、图像、3D点
  242. cameras = read_cameras_text(os.path.join(path, "cameras" + ext))
  243. images = read_images_text(os.path.join(path, "images" + ext))
  244. points3D = read_points3D_text(os.path.join(path, "points3D") + ext)
  245. else:
  246. cameras = read_cameras_binary(os.path.join(path, "cameras" + ext))
  247. images = read_images_binary(os.path.join(path, "images" + ext))
  248. points3D = read_points3d_binary(os.path.join(path, "points3D") + ext)
  249. return cameras, images, points3D
  250. def qvec2rotmat(qvec):
  251. return np.array([
  252. [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
  253. 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
  254. 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
  255. [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
  256. 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
  257. 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
  258. [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
  259. 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
  260. 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
  261. def rotmat2qvec(R):
  262. Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
  263. K = np.array([
  264. [Rxx - Ryy - Rzz, 0, 0, 0],
  265. [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
  266. [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
  267. [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
  268. eigvals, eigvecs = np.linalg.eigh(K)
  269. qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
  270. if qvec[0] < 0:
  271. qvec *= -1
  272. return qvec
  273. if __name__ == '__main__':
  274. parser = argparse.ArgumentParser(description='Convert colmap results into input for PatchmatchNet')
  275. parser.add_argument('--folder', default='./data',type=str, help='Project dir.')
  276. parser.add_argument('--theta0', type=float, default=5)
  277. parser.add_argument('--sigma1', type=float, default=1)
  278. parser.add_argument('--sigma2', type=float, default=10)
  279. # 测试程序是否可用,如果置此位为true则不保存结果
  280. parser.add_argument('--test', action='store_true', default=False, help='If set, do not write to file.')
  281. # 转换格式,将图片转换成jpg格式
  282. parser.add_argument('--convert_format', action='store_true', default=False, help='If set, convert image to jpg format.')
  283. args = parser.parse_args()
  284. # 图片路径,即这个路径下要有图像
  285. image_dir = os.path.join(args.folder, 'images')
  286. # 位姿路径
  287. model_dir = os.path.join(args.folder, 'sparse')
  288. # 这两个文件夹是我们要保存的结果
  289. cam_dir = os.path.join(args.folder, 'cams')
  290. renamed_dir = os.path.join(args.folder, 'images')
  291. # 相机参数、图像、3D点读入到变量中
  292. cameras, images, points3d = read_model(model_dir, '.txt')
  293. #cameras, images, points3d = read_model(model_dir, '.bin')
  294. num_images = len(list(images.items()))
  295. param_type = {
  296. 'SIMPLE_PINHOLE': ['f', 'cx', 'cy'],
  297. 'PINHOLE': ['fx', 'fy', 'cx', 'cy'],
  298. 'SIMPLE_RADIAL': ['f', 'cx', 'cy', 'k'],
  299. 'SIMPLE_RADIAL_FISHEYE': ['f', 'cx', 'cy', 'k'],
  300. 'RADIAL': ['f', 'cx', 'cy', 'k1', 'k2'],
  301. 'RADIAL_FISHEYE': ['f', 'cx', 'cy', 'k1', 'k2'],
  302. 'OPENCV': ['fx', 'fy', 'cx', 'cy', 'k1', 'k2', 'p1', 'p2'],
  303. 'OPENCV_FISHEYE': ['fx', 'fy', 'cx', 'cy', 'k1', 'k2', 'k3', 'k4'],
  304. 'FULL_OPENCV': ['fx', 'fy', 'cx', 'cy', 'k1', 'k2', 'p1', 'p2', 'k3', 'k4', 'k5', 'k6'],
  305. 'FOV': ['fx', 'fy', 'cx', 'cy', 'omega'],
  306. 'THIN_PRISM_FISHEYE': ['fx', 'fy', 'cx', 'cy', 'k1', 'k2', 'p1', 'p2', 'k3', 'k4', 'sx1', 'sy1']
  307. }
  308. # intrinsic
  309. intrinsic = {}
  310. for camera_id, cam in cameras.items():
  311. params_dict = {key: value for key, value in zip(param_type[cam.model], cam.params)}
  312. print(cam.model)
  313. if 'f' in param_type[cam.model]:
  314. params_dict['fx'] = params_dict['f']
  315. params_dict['fy'] = params_dict['f']
  316. i = np.array([
  317. [params_dict['fx'], 0, params_dict['cx']],
  318. [0, params_dict['fy'], params_dict['cy']],
  319. [0, 0, 1]
  320. ])
  321. intrinsic[camera_id] = i
  322. print('intrinsic[0]\n', intrinsic, end='\n\n')
  323. # extrinsic
  324. extrinsic = {}
  325. for image_id, image in images.items():
  326. e = np.zeros((4, 4))
  327. e[:3, :3] = qvec2rotmat(image.qvec)
  328. e[:3, 3] = image.tvec
  329. e[3, 3] = 1
  330. extrinsic[image_id] = e
  331. print('extrinsic[1]\n', extrinsic[1], end='\n\n')
  332. # depth range and interval
  333. depth_ranges = {}
  334. for i in range(num_images):
  335. zs = []
  336. for p3d_id in images[i+1].point3D_ids:
  337. if p3d_id == -1:
  338. continue
  339. transformed = np.matmul(extrinsic[i+1], [points3d[p3d_id].xyz[0], points3d[p3d_id].xyz[1], points3d[p3d_id].xyz[2], 1])
  340. zs.append(np.asscalar(transformed[2]))
  341. zs_sorted = sorted(zs)
  342. # relaxed depth range
  343. depth_min = zs_sorted[int(len(zs) * .01)]
  344. depth_max = zs_sorted[int(len(zs) * .99)]
  345. depth_ranges[i+1] = (depth_min, depth_max)
  346. print('depth_ranges[1]\n', depth_ranges[1], end='\n\n')
  347. # view selection
  348. score = np.zeros((len(images), len(images)))
  349. queue = []
  350. for i in range(len(images)):
  351. for j in range(i + 1, len(images)):
  352. queue.append((i, j))
  353. # def calc_score(inputs):
  354. # i, j = inputs
  355. # id_i = images[i+1].point3D_ids
  356. # id_j = images[j+1].point3D_ids
  357. # id_intersect = [it for it in id_i if it in id_j]
  358. # cam_center_i = -np.matmul(extrinsic[i+1][:3, :3].transpose(), extrinsic[i+1][:3, 3:4])[:, 0]
  359. # cam_center_j = -np.matmul(extrinsic[j+1][:3, :3].transpose(), extrinsic[j+1][:3, 3:4])[:, 0]
  360. # score = 0
  361. # for pid in id_intersect:
  362. # if pid == -1:
  363. # continue
  364. # p = points3d[pid].xyz
  365. # theta = (180 / np.pi) * np.arccos(np.dot(cam_center_i - p, cam_center_j - p) / np.linalg.norm(cam_center_i - p) / np.linalg.norm(cam_center_j - p))
  366. # score += np.exp(-(theta - args.theta0) * (theta - args.theta0) / (2 * (args.sigma1 if theta <= args.theta0 else args.sigma2) ** 2))
  367. # return i, j, score
  368. # p = mp.Pool(processes=mp.cpu_count())
  369. # result = p.map(calc_score, queue)
  370. for i, j in queue:
  371. id_i = images[i+1].point3D_ids
  372. id_j = images[j+1].point3D_ids
  373. id_intersect = [it for it in id_i if it in id_j]
  374. cam_center_i = -np.matmul(extrinsic[i+1][:3, :3].transpose(), extrinsic[i+1][:3, 3:4])[:, 0]
  375. cam_center_j = -np.matmul(extrinsic[j+1][:3, :3].transpose(), extrinsic[j+1][:3, 3:4])[:, 0]
  376. s = 0
  377. for pid in id_intersect:
  378. if pid == -1:
  379. continue
  380. p = points3d[pid].xyz
  381. theta = (180 / np.pi) * np.arccos(np.dot(cam_center_i - p, cam_center_j - p) / np.linalg.norm(cam_center_i - p) / np.linalg.norm(cam_center_j - p))
  382. s += np.exp(-(theta - args.theta0) * (theta - args.theta0) / (2 * (args.sigma1 if theta <= args.theta0 else args.sigma2) ** 2))
  383. score[i, j] = s
  384. score[j, i] = s
  385. view_sel = []
  386. for i in range(len(images)):
  387. sorted_score = np.argsort(score[i])[::-1]
  388. view_sel.append([(k, score[i, k]) for k in sorted_score[:10]])
  389. print('view_sel[0]\n', view_sel[0], end='\n\n')
  390. # write
  391. try:
  392. os.makedirs(cam_dir)
  393. except os.error:
  394. print(cam_dir + ' already exist.')
  395. for i in range(num_images):
  396. with open(os.path.join(cam_dir, '%08d_cam.txt' % i), 'w') as f:
  397. f.write('extrinsic\n')
  398. for j in range(4):
  399. for k in range(4):
  400. f.write(str(extrinsic[i+1][j, k]) + ' ')
  401. f.write('\n')
  402. f.write('\nintrinsic\n')
  403. for j in range(3):
  404. for k in range(3):
  405. f.write(str(intrinsic[images[i+1].camera_id][j, k]) + ' ')
  406. f.write('\n')
  407. f.write('\n%f %f \n' % (depth_ranges[i+1][0], depth_ranges[i+1][1]))
  408. with open(os.path.join(args.folder, 'pair.txt'), 'w') as f:
  409. f.write('%d\n' % len(images))
  410. for i, sorted_score in enumerate(view_sel):
  411. f.write('%d\n%d ' % (i, len(sorted_score)))
  412. for image_id, s in sorted_score:
  413. f.write('%d %f ' % (image_id, s))
  414. f.write('\n')
  415. for i in range(num_images):
  416. if args.convert_format:
  417. img = cv2.imread(os.path.join(image_dir, images[i+1].name))
  418. cv2.imwrite(os.path.join(renamed_dir, '%08d.jpg' % i), img)
  419. else:
  420. shutil.copyfile(os.path.join(image_dir, images[i+1].name), os.path.join(renamed_dir, '%08d.jpg' % i))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/103525
推荐阅读
相关标签
  

闽ICP备14008679号