hongxiaoy commited on
Commit
d46080c
1 Parent(s): bc160aa

Create generate_gt.py

Browse files
Files changed (1) hide show
  1. generate_gt.py +443 -0
generate_gt.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from functools import partial
3
+ import os
4
+ from tqdm import tqdm
5
+ import glob
6
+ import numpy as np
7
+ import cv2
8
+ from sklearn.neighbors import KDTree
9
+ from collections import Counter
10
+ from PIL import Image
11
+ from mmengine import track_parallel_progress
12
+
13
+
14
+ def load_voxels(path):
15
+ """Load voxel labels from file.
16
+
17
+ Args:
18
+ path (str): The path of the voxel labels file.
19
+
20
+ Returns:
21
+ ndarray: The voxel labels with shape (N, 4), 4 is for [x, y, z, label].
22
+ """
23
+ labels = np.load(path)
24
+ if labels.shape[1] == 7:
25
+ labels = labels[:, [0, 1, 2, 6]]
26
+
27
+ return labels
28
+
29
+
30
+ def _downsample_label(label, voxel_size=(240, 144, 240), downscale=4):
31
+ r"""downsample the labeled data,
32
+ code taken from https://github.com/waterljwant/SSC/blob/master/dataloaders/dataloader.py#L262
33
+ Shape:
34
+ label, (240, 144, 240)
35
+ label_downscale, if downsample==4, then (60, 36, 60)
36
+ """
37
+ if downscale == 1:
38
+ return label
39
+ ds = downscale
40
+ small_size = (
41
+ voxel_size[0] // ds,
42
+ voxel_size[1] // ds,
43
+ voxel_size[2] // ds,
44
+ ) # small size
45
+ label_downscale = np.zeros(small_size, dtype=np.uint8)
46
+ empty_t = 0.95 * ds * ds * ds # threshold
47
+ s01 = small_size[0] * small_size[1]
48
+ label_i = np.zeros((ds, ds, ds), dtype=np.int32)
49
+
50
+ for i in range(small_size[0] * small_size[1] * small_size[2]):
51
+ z = int(i / s01)
52
+ y = int((i - z * s01) / small_size[0])
53
+ x = int(i - z * s01 - y * small_size[0])
54
+
55
+ label_i[:, :, :] = label[
56
+ x * ds : (x + 1) * ds, y * ds : (y + 1) * ds, z * ds : (z + 1) * ds
57
+ ]
58
+ label_bin = label_i.flatten()
59
+
60
+ zero_count_0 = np.array(np.where(label_bin == 0)).size
61
+ zero_count_255 = np.array(np.where(label_bin == 255)).size
62
+
63
+ zero_count = zero_count_0 + zero_count_255
64
+ if zero_count > empty_t:
65
+ label_downscale[x, y, z] = 0 if zero_count_0 > zero_count_255 else 255
66
+ else:
67
+ label_i_s = label_bin[
68
+ np.where(np.logical_and(label_bin > 0, label_bin < 255))
69
+ ]
70
+ label_downscale[x, y, z] = np.argmax(np.bincount(label_i_s))
71
+ return label_downscale
72
+
73
+
74
+ # 1. 从列表中删掉 pose 为 nan 的场景
75
+ def clear_posed_images(scene_list):
76
+
77
+ # 从 mmdet3d 处理得到的有问题场景sens列表
78
+ # TODO: how to generate wrong_scenes.txt?
79
+ with open('wrong_scenes.txt', 'r') as f:
80
+ wrongs = f.readlines()
81
+ # TODO: how to generate not_aligns.txt?
82
+ with open('not_aligns.txt', 'r') as f:
83
+ not_aligns = f.readlines()
84
+
85
+ # 清理为只有场景名称
86
+ wrongs = [w.split('/')[1] for w in wrongs]
87
+ wrongs = sorted(list(set(wrongs))) # 212 scenes
88
+
89
+ not_aligns = sorted([s.strip() for s in not_aligns])
90
+
91
+ # 除去这些场景的图片
92
+ scene_list = sorted(list(set(scene_list) - set(wrongs)))
93
+ scene_list = sorted(list(set(scene_list) - set(not_aligns)))
94
+
95
+ return scene_list
96
+
97
+
98
+ # 2. 生成子场景的体素标签
99
+ def generate_subvoxels(name):
100
+ # print(name)
101
+
102
+ # basic scene parameters
103
+ height_belowfloor = - 0.05
104
+ voxUnit = 0.08 # 0.05 m
105
+ voxSizeCam = np.array([60, 60, 60]) # 96 x 96 x 96 voxs x y z in cam coordinate
106
+ voxSize = np.array([60, 60, 36]) # 96 x 96 x 64 voxs x y z in world coordinate
107
+ voxRangeExtremesCam = np.stack([-voxSizeCam * voxUnit / 2.,
108
+ -voxSizeCam * voxUnit / 2. + voxSizeCam * voxUnit]).T
109
+ voxRangeExtremesCam[-1, 0] = 0
110
+ voxRangeExtremesCam[-1, 1] = 6.8
111
+ # voxel origin in cam coordinate x y z in cam coordinate
112
+ voxOriginCam = np.mean(voxRangeExtremesCam, axis=1, keepdims=True)
113
+
114
+ # for name in tqdm(scenes_name):
115
+ poses = glob.glob(os.path.join('../scannet/posed_images', name, '*.txt'))
116
+ poses = sorted(poses)
117
+ if len(poses) == 0:
118
+ return
119
+
120
+ imgs = glob.glob(os.path.join('../scannet/posed_images', name, '*.jpg'))
121
+ imgs = sorted(imgs)
122
+
123
+ intrinsic = poses.pop(-1)
124
+ intrinsic = np.loadtxt(intrinsic)
125
+
126
+ for pose, img in zip(poses, imgs):
127
+ framename = os.path.basename(pose)[:-4]
128
+ extCam2World = np.loadtxt(pose)
129
+ # if os.path.exists(f'preprocessed_voxels/{name}/{framename}.npy'):
130
+ # continue
131
+ if np.isneginf(extCam2World).any():
132
+ continue
133
+ img = cv2.imread(img)
134
+ h, w, c = img.shape
135
+
136
+ voxOriginWorld = extCam2World[:3, :3] @ voxOriginCam + extCam2World[:3, -1:]
137
+ delta = np.array([[voxSize[0]/2*voxUnit], [voxSize[1]/2*voxUnit], [voxSize[2]/2*voxUnit]])
138
+ voxOriginWorld -= delta
139
+ voxOriginWorld[2, 0] = height_belowfloor
140
+
141
+ if os.path.exists(f"../completescannet/preprocessed/{name}.npy"):
142
+ scene_voxels = load_voxels(f"../completescannet/preprocessed/{name}.npy")
143
+ else:
144
+ continue
145
+ scene_voxels_delta = np.abs(scene_voxels[:, :3] - voxOriginWorld.reshape(-1)) # TODO: abs? or 0<=x<=4.8
146
+ mask = np.logical_and(scene_voxels_delta[:, 0] <=4.8,
147
+ np.logical_and(scene_voxels_delta[:, 1] <= 4.8,
148
+ scene_voxels_delta[:, 2] <= 4.8))
149
+ voxels = scene_voxels[mask]
150
+
151
+ xs = np.arange(voxOriginWorld[0, 0], voxOriginWorld[0, 0] + 100*voxUnit, voxUnit)[:voxSize[0]]
152
+ ys = np.arange(voxOriginWorld[1, 0], voxOriginWorld[1, 0] + 100*voxUnit, voxUnit)[:voxSize[1]]
153
+ zs = np.arange(voxOriginWorld[2, 0], voxOriginWorld[2, 0] + 100*voxUnit, voxUnit)[:voxSize[2]]
154
+ gridPtsWorldX, gridPtsWorldY, gridPtsWorldZ = np.meshgrid(xs, ys, zs)
155
+ gridPtsWorld = np.stack([gridPtsWorldX.flatten(),
156
+ gridPtsWorldY.flatten(),
157
+ gridPtsWorldZ.flatten()], axis=1)
158
+
159
+ gridPtsLabel = np.zeros((gridPtsWorld.shape[0]))
160
+
161
+ if voxels.shape[0] <= 0:
162
+ continue
163
+
164
+ kdtree = KDTree(voxels[:, :3], leaf_size=10)
165
+ dist, ind = kdtree.query(gridPtsWorld)
166
+ dist, ind = dist.reshape(-1), ind.reshape(-1)
167
+ mask = dist <= voxUnit
168
+ gridPtsLabel[mask] = voxels[:, -1][ind[mask]]
169
+
170
+ gridPtsWorld = np.hstack([gridPtsWorld, gridPtsLabel.reshape(-1, 1)])
171
+
172
+ g = gridPtsWorld[:, -1].reshape(voxSize[0], voxSize[1], voxSize[2])
173
+ g_not_0 = np.where(g > 0)
174
+ if len(g_not_0) == 0:
175
+ continue
176
+ g_not_0_x = g_not_0[0]
177
+ g_not_0_y = g_not_0[1]
178
+ if len(g_not_0_x) == 0:
179
+ continue
180
+ if len(g_not_0_y) == 0:
181
+ continue
182
+ valid_x_min = g_not_0_x.min()
183
+ valid_x_max = g_not_0_x.max()
184
+ valid_y_min = g_not_0_y.min()
185
+ valid_y_max = g_not_0_y.max()
186
+ # print(valid_x_min, valid_x_max, valid_y_min, valid_y_max)
187
+ # print(valid_x_min, valid_x_max, valid_y_min, valid_y_max)
188
+ mask = np.zeros_like(g)
189
+ if valid_x_min != valid_x_max and valid_y_min != valid_y_max:
190
+ mask[valid_x_min:valid_x_max, valid_y_min:valid_y_max, :] = 1
191
+ mask = 1 - mask #
192
+ mask = mask.astype(np.bool_)
193
+ g[mask] = 255
194
+ else:
195
+ continue
196
+ gridPtsWorld[:, -1] = g.reshape(-1)
197
+
198
+ voxels_cam = (np.linalg.inv(extCam2World)[:3, :3] @ gridPtsWorld[:, :3].T \
199
+ + np.linalg.inv(extCam2World)[:3, -1:]).T
200
+ voxels_pix = (intrinsic[:3, :3] @ voxels_cam.T).T
201
+ voxels_pix = voxels_pix / voxels_pix[:, -1:]
202
+ mask = np.logical_and(voxels_pix[:, 0] >= 0,
203
+ np.logical_and(voxels_pix[:, 0] < w,
204
+ np.logical_and(voxels_pix[:, 1] >= 0,
205
+ np.logical_and(voxels_pix[:, 1] < h,
206
+ voxels_cam[:, 2] > 0))))
207
+ inroom = gridPtsWorld[:, -1] != 255
208
+ mask = np.logical_and(~mask, inroom)
209
+ gridPtsWorld[mask, -1] = 0
210
+
211
+
212
+ os.makedirs(f'preprocessed_voxels/{name}', exist_ok=True)
213
+ np.save(f'preprocessed_voxels/{name}/{framename}.npy', gridPtsWorld)
214
+ # print("Save gt to", f'preprocessed_voxels/{name}/{framename}.npy')
215
+
216
+
217
+ # 3. 生成那些类别少于2, 有效语义体素数量少于5%的场景 和相机位姿还是有错误的那些场景
218
+ def get_badposescene():
219
+ bad_scenes = []
220
+ scenenames = glob.glob(os.path.join('../completescannet/preprocessed', '*.npy'))
221
+ scenenames = sorted(scenenames)
222
+ for name in tqdm(scenenames):
223
+ voxels = load_voxels(name)
224
+ voxelrange = [voxels[:, 0].min(),
225
+ voxels[:, 1].min(),
226
+ voxels[:, 2].min(),
227
+ voxels[:, 0].max(),
228
+ voxels[:, 1].max(),
229
+ voxels[:, 2].max(),]
230
+ print('vox range: ', voxelrange)
231
+ basename = os.path.basename(name)[:-4]
232
+
233
+ npys = glob.glob(os.path.join('preprocessed_voxels', basename, '*.npy'))
234
+ npys = sorted(npys)
235
+
236
+ for npy in npys:
237
+ jpg = os.path.basename(npy)[:-4]+'.txt'
238
+ cam_pose_path = os.path.join('../scannet/posed_images', basename, jpg)
239
+ cam_pose = np.loadtxt(cam_pose_path)
240
+ cam_origin = (cam_pose[:3, :3] @ np.zeros((1, 3)).T + cam_pose[:3, -1:]).T
241
+ print('cam_o: ', cam_origin)
242
+
243
+ x, y, z = cam_origin[0]
244
+ xmin, ymin, zmin, xmax, ymax, zmax = voxelrange
245
+ zmax = 3.0
246
+
247
+ in_x = xmin < x < xmax
248
+ in_y = ymin < y < ymax
249
+ in_z = zmin < z < zmax
250
+
251
+ valid = in_x & in_y & in_z
252
+
253
+ if not valid:
254
+ bad_scenes.append(npy)
255
+ bad_scenes.append('\n')
256
+ # with open('bad_scenes.txt', 'w') as f:
257
+ # f.writelines(bad_scenes)
258
+ # pprint(bad_scenes)
259
+ scene_path = os.path.join('preprocessed_voxels', name)
260
+ npys = glob.glob(os.path.join(scene_path, '*.npy'))
261
+ npys = sorted(npys)
262
+ for vox in npys:
263
+ voxels = np.load(vox)
264
+ labels = voxels[:, -1].tolist()
265
+ cnt = Counter(labels)
266
+ total = 0
267
+ valid = 0
268
+ for i in cnt.keys():
269
+ total += cnt[i]
270
+ if i != 0.0 and i != 255.0:
271
+ valid += 1
272
+ outroom = cnt[255.0]
273
+ empty = cnt[0.0]
274
+ if valid < 2:
275
+ bad_scenes.append(vox)
276
+ continue
277
+
278
+ if (outroom / total) > 0.95:
279
+ bad_scenes.append(vox)
280
+ continue
281
+
282
+ if (empty / total) > 0.95:
283
+ bad_scenes.append(vox)
284
+ continue
285
+
286
+ if ((empty + outroom) / total) > 0.95:
287
+ bad_scenes.append(vox)
288
+ continue
289
+ with open('bad_scenes.txt', 'w') as f:
290
+ f.writelines(bad_scenes)
291
+ # print(bad_scenes)
292
+
293
+
294
+ # 4. 整合数据
295
+ def gather_data(scene_list):
296
+
297
+
298
+
299
+ scenes = os.listdir('preprocessed_voxels')
300
+ scenes = set(sorted(scenes))
301
+ scenes = sorted(list(set(scene_list) & scenes))
302
+
303
+ for scene in scenes:
304
+ scene_path = os.path.join('preprocessed_voxels', scene)
305
+ scene_name = scene
306
+
307
+ os.makedirs(os.path.join('gathered_data', scene_name), exist_ok=True)
308
+
309
+ npys = glob.glob(os.path.join(scene_path, '*.npy'))
310
+ npys = sorted(npys)
311
+
312
+ for npy in npys:
313
+ data = {}
314
+ npy_name = os.path.basename(npy)[:-4]
315
+ npy_path = npy
316
+
317
+ img_path = os.path.join('../scannet/posed_images', scene_name, npy_name+'.jpg')
318
+ img_path = os.path.abspath(img_path)
319
+ depth_path = os.path.join('../scannet/posed_images', scene_name, npy_name+'.png')
320
+ depth_path = os.path.abspath(depth_path)
321
+ cam_pose_path = os.path.join('../scannet/posed_images', scene_name, npy_name+'.txt')
322
+ cam_intrin_path = os.path.join('../scannet/posed_images', scene_name, 'intrinsic.txt')
323
+
324
+ img = cv2.imread(img_path)
325
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
326
+ depth_img = Image.open(depth_path).convert('I;16')
327
+ depth_img = np.array(depth_img) / 1000.0
328
+ data['img'] = img_path
329
+ data['depth_gt'] = depth_path
330
+ cam_pose = np.loadtxt(cam_pose_path)
331
+ data['cam_pose'] = cam_pose
332
+ intrinsic = np.loadtxt(cam_intrin_path)
333
+ data['intrinsic'] = intrinsic
334
+
335
+ target_1_4 = np.load(npy_path)
336
+ data['target_1_4'] = target_1_4[:, -1].reshape(60, 60, 36)
337
+
338
+ voxel_origin = target_1_4[:, 0].min(), target_1_4[:, 1].min(), target_1_4[:, 2].min()
339
+ data['voxel_origin'] = voxel_origin
340
+
341
+ target_1_16 = _downsample_label(target_1_4[:, -1].reshape(60, 60, 36), (60, 60, 36), 4)
342
+ data['target_1_16'] = target_1_16
343
+
344
+ savepth = os.path.join('gathered_data', scene_name, npy_name+'.pkl')
345
+ print(savepth)
346
+ with open(savepth, "wb") as handle:
347
+ import pickle
348
+ pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
349
+ # np.save(savepth, data)
350
+
351
+
352
+ def generate_train_val_list():
353
+ with open('not_aligns.txt', 'r') as f:
354
+ not_aligns = f.readlines()
355
+ for i in range(len(not_aligns)):
356
+ not_aligns[i] = not_aligns[i].strip()
357
+
358
+ scan_names = os.listdir('gathered_data')
359
+ start = len(scan_names)
360
+ scan_names = list(set(scan_names) - set(not_aligns))
361
+ end = len(scan_names)
362
+
363
+ used_scan_names = sorted(scan_names)
364
+ used_scan_names.pop(-1)
365
+ with open('used_scan_names.txt', 'w') as f:
366
+ f.writelines('\n'.join(used_scan_names))
367
+
368
+ train_used_subscenes = []
369
+ val_used_subscenes = []
370
+ for s in used_scan_names:
371
+ paths = glob.glob(os.path.join('gathered_data', s, '*.pkl'))
372
+ paths = sorted(paths)
373
+ np.random.seed(21)
374
+ paths = np.random.permutation(paths)
375
+ n_paths = len(paths)
376
+ n_train = int(n_paths * 0.7)
377
+ train_paths = paths[:n_train]
378
+ val_paths = paths[n_train:]
379
+
380
+ train_used_subscenes.extend(train_paths)
381
+ val_used_subscenes.extend(val_paths)
382
+
383
+ with open('train_subscenes.txt', 'w') as f:
384
+ f.writelines('\n'.join(sorted(train_used_subscenes)))
385
+ with open('val_subscenes.txt', 'w') as f:
386
+ f.writelines('\n'.join(sorted(val_used_subscenes)))
387
+
388
+
389
+ def parse_args():
390
+ parser = argparse.ArgumentParser(description='Prepare for the ScanNetOcc Dataset.')
391
+ parser.add_argument('--outpath', type=str, required=False, help='Output path of the generated GT labels.')
392
+ args = parser.parse_args()
393
+ return args
394
+
395
+
396
+ def main():
397
+ # args = parse_args()
398
+ # if not os.path.exists(args.outpath):
399
+ # os.makedirs(args.outpath, exist_ok=True)
400
+
401
+ scene_name_list = sorted(os.listdir('../scannet/posed_images'))
402
+
403
+ # scene_name_list = sorted(list(set(scene_name_list) - set(not_aligns)))
404
+
405
+ failed_scene = []
406
+
407
+ # Step 1:
408
+ scene_name_list = clear_posed_images(scene_name_list)
409
+ print("===== Finish Step 1 =====")
410
+
411
+ # Step 2:
412
+ track_parallel_progress(generate_subvoxels,
413
+ scene_name_list,
414
+ nproc=12)
415
+ print("===== Finish Step 2 =====")
416
+
417
+ # # Step 3:
418
+ # TODO: what is bad pose scene?
419
+ get_badposescene()
420
+ with open('bad_scenes.txt', 'r') as f:
421
+ bs = f.readlines()
422
+ bs = [b.strip() for b in bs]
423
+ bs = list(set(bs))
424
+ # TODO: Remove or not?
425
+ for s in bs:
426
+ ss = s.replace('\n', '')
427
+ print(ss, "to be removed")
428
+ # path = os.path.join(*ss)
429
+ # print(path)
430
+ os.remove(ss)
431
+ print("===== Finish Step 3 =====")
432
+
433
+ # Step 4:
434
+ gather_data(scene_name_list)
435
+ print("===== Finish Step 4 =====")
436
+
437
+ # Step 5:
438
+ generate_train_val_list()
439
+ print("===== Finish Step 5 =====")
440
+
441
+
442
+ if __name__ == "__main__":
443
+ main()