Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

colmap2nerf.py 7.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. import os
  2. import cv2
  3. import json
  4. import math
  5. import click
  6. import numpy as np
  7. from pathlib import Path
  8. def variance_of_laplacian(image):
  9. return cv2.Laplacian(image, cv2.CV_64F).var()
  10. def sharpness(imagePath):
  11. image = cv2.imread(imagePath)
  12. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  13. fm = variance_of_laplacian(gray)
  14. return fm
  15. def qvec2rotmat(qvec):
  16. return np.array(
  17. [
  18. [
  19. 1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
  20. 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
  21. 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],
  22. ],
  23. [
  24. 2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
  25. 1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
  26. 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],
  27. ],
  28. [
  29. 2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
  30. 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
  31. 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,
  32. ],
  33. ]
  34. )
  35. def rotmat(a, b):
  36. a, b = a / np.linalg.norm(a), b / np.linalg.norm(b)
  37. v = np.cross(a, b)
  38. c = np.dot(a, b)
  39. # handle exception for the opposite direction input
  40. if c < -1 + 1e-10:
  41. return rotmat(a + np.random.uniform(-1e-2, 1e-2, 3), b)
  42. s = np.linalg.norm(v)
  43. kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
  44. return np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s**2 + 1e-10))
  45. def closest_point_2_lines(oa, da, ob, db):
  46. """
  47. Returns point closest to both rays of form o+t*d,
  48. and a weight factor that goes to 0 if the lines are parallel
  49. """
  50. da = da / np.linalg.norm(da)
  51. db = db / np.linalg.norm(db)
  52. c = np.cross(da, db)
  53. denom = np.linalg.norm(c) ** 2
  54. t = ob - oa
  55. ta = np.linalg.det([t, db, c]) / (denom + 1e-10)
  56. tb = np.linalg.det([t, da, c]) / (denom + 1e-10)
  57. if ta > 0:
  58. ta = 0
  59. if tb > 0:
  60. tb = 0
  61. return (oa + ta * da + ob + tb * db) * 0.5, denom
  62. def get_colmap_cameras(text_folder):
  63. with open(os.path.join(text_folder, "cameras.txt"), "r") as f:
  64. for line in f:
  65. if line[0] == "#":
  66. continue
  67. els = line.split(" ")
  68. w, h = float(els[2]), float(els[3])
  69. fl_x, fl_y = float(els[4]), float(els[4])
  70. k1, k2, p1, p2 = 0, 0, 0, 0
  71. cx, cy = w / 2, h / 2
  72. if els[1] == "SIMPLE_PINHOLE":
  73. cx, cy = float(els[5]), float(els[6])
  74. elif els[1] == "PINHOLE":
  75. fl_y = float(els[5])
  76. cx = float(els[6]), float(els[7])
  77. elif els[1] == "SIMPLE_RADIAL":
  78. cx, cy = float(els[5]), float(els[6])
  79. k1 = float(els[7])
  80. elif els[1] == "RADIAL":
  81. cx, cy = float(els[5]), float(els[6])
  82. k1, k2 = float(els[7]), float(els[8])
  83. elif els[1] == "OPENCV":
  84. fl_y = float(els[5])
  85. cx, cy = float(els[6]), float(els[7])
  86. k1, k2 = float(els[8]), float(els[9])
  87. p1, p2 = float(els[10]), float(els[11])
  88. else:
  89. print("unknown camera model ", els[1])
  90. angle_x = math.atan(w / (fl_x * 2)) * 2
  91. angle_y = math.atan(h / (fl_y * 2)) * 2
  92. fovx = angle_x * 180 / math.pi
  93. fovy = angle_y * 180 / math.pi
  94. print(
  95. f"camera:"
  96. f"\n\tres={w,h}"
  97. f"\n\tcenter={cx,cy}\n\t"
  98. f"focal={fl_x,fl_y}\n\t"
  99. f"fov={fovx,fovy}\n\t"
  100. f"k={k1,k2} "
  101. f"p={p1,p2} "
  102. )
  103. return w, h, cx, cy, fl_x, fl_y, fovx, fovy, k1, k2, p1, p2, angle_x, angle_y
  104. def get_colmap_images(text_folder, image_folder, out):
  105. with open(os.path.join(text_folder, "images.txt"), "r") as f:
  106. i = 0
  107. bottom = np.array([0.0, 0.0, 0.0, 1.0]).reshape([1, 4])
  108. up = np.zeros(3)
  109. for line in f:
  110. line = line.strip()
  111. if line[0] == "#":
  112. continue
  113. i = i + 1
  114. if i % 2 == 1:
  115. elems = line.split(" ")
  116. image_rel = os.path.relpath(image_folder)
  117. name = str(f"./{image_rel}/{'_'.join(elems[9:])}")
  118. b = sharpness(name)
  119. qvec = np.array(tuple(map(float, elems[1:5])))
  120. tvec = np.array(tuple(map(float, elems[5:8])))
  121. R = qvec2rotmat(-qvec)
  122. t = tvec.reshape([3, 1])
  123. m = np.concatenate([np.concatenate([R, t], 1), bottom], 0)
  124. c2w = np.linalg.inv(m)
  125. c2w[0:3, 2] *= -1 # flip the y and z axis
  126. c2w[0:3, 1] *= -1
  127. c2w = c2w[[1, 0, 2, 3], :] # swap y and z
  128. c2w[2, :] *= -1 # flip whole world upside down
  129. up += c2w[0:3, 1]
  130. file_path = f"../images/{Path(name).stem}"
  131. frame = {
  132. "file_path": file_path,
  133. "sharpness": b,
  134. "transform_matrix": c2w,
  135. }
  136. out["frames"].append(frame)
  137. return out, up
  138. @click.command()
  139. @click.option("--aabb_scale", default=4)
  140. @click.option("--image_folder", default="data/processed/images")
  141. @click.option("--colmap_text_folder", default="data/processed/colmap_db/colmap_text")
  142. @click.option("--output", default="data/processed/configs/nerf_transforms.json")
  143. def colmap2nerf(aabb_scale, image_folder, colmap_text_folder, output):
  144. """
  145. Convert colmap format to nerf
  146. @param aabb_scale: large scene scale factor.
  147. 1=scene fits in unit cube; power of 2 up to 16
  148. @param image_folder: input path to the images
  149. @param colmap_text_folder: path to colmap text folder
  150. @param output: name of output file
  151. """
  152. print("start colmap2nerf")
  153. (
  154. w,
  155. h,
  156. cx,
  157. cy,
  158. fl_x,
  159. fl_y,
  160. fovx,
  161. fovy,
  162. k1,
  163. k2,
  164. p1,
  165. p2,
  166. angle_x,
  167. angle_y,
  168. ) = get_colmap_cameras(colmap_text_folder)
  169. out = {
  170. "camera_angle_x": angle_x,
  171. "camera_angle_y": angle_y,
  172. "fl_x": fl_x,
  173. "fl_y": fl_y,
  174. "k1": k1,
  175. "k2": k2,
  176. "p1": p1,
  177. "p2": p2,
  178. "cx": cx,
  179. "cy": cy,
  180. "w": w,
  181. "h": h,
  182. "aabb_scale": aabb_scale,
  183. "frames": [],
  184. }
  185. out, up = get_colmap_images(colmap_text_folder, image_folder, out)
  186. nframes = len(out["frames"])
  187. # don't keep colmap coords - reorient the scene to be easier to work with
  188. up = up / np.linalg.norm(up)
  189. R = rotmat(up, [0, 0, 1]) # rotate up vector to [0,0,1]
  190. R = np.pad(R, [0, 1])
  191. R[-1, -1] = 1
  192. for f in out["frames"]:
  193. f["transform_matrix"] = np.matmul(
  194. R, f["transform_matrix"]
  195. ) # rotate up to be the z axis
  196. # find a central point they are all looking at
  197. print("computing center of attention...")
  198. totw = 0.0
  199. totp = np.array([0.0, 0.0, 0.0])
  200. for f in out["frames"]:
  201. mf = f["transform_matrix"][0:3, :]
  202. for g in out["frames"]:
  203. mg = g["transform_matrix"][0:3, :]
  204. p, w = closest_point_2_lines(mf[:, 3], mf[:, 2], mg[:, 3], mg[:, 2])
  205. if w > 0.01:
  206. totp += p * w
  207. totw += w
  208. totp /= totw
  209. for f in out["frames"]:
  210. f["transform_matrix"][0:3, 3] -= totp
  211. avglen = 0.0
  212. for f in out["frames"]:
  213. avglen += np.linalg.norm(f["transform_matrix"][0:3, 3])
  214. avglen /= nframes
  215. print("avg camera distance from origin", avglen)
  216. for f in out["frames"]:
  217. f["transform_matrix"][0:3, 3] *= 4.0 / avglen # scale to "nerf sized"
  218. for f in out["frames"]:
  219. f["transform_matrix"] = f["transform_matrix"].tolist()
  220. print(nframes, "frames")
  221. print(f"writing {output}")
  222. with open(output, "w") as outfile:
  223. json.dump(out, outfile, indent=2)
  224. if __name__ == "__main__":
  225. colmap2nerf()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...