forked from yangyanli/PointCNN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract_scannet_objs.py
347 lines (241 loc) · 9.96 KB
/
extract_scannet_objs.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#!/usr/bin/python3
"""Convert original Scannet data to PointCNN Classification dataset"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
import plyfile
from plyfile import PlyData
import argparse
import numpy as np
def dir(root, type='f', addroot=True):
dirList = []
fileList = []
root = root + "/"
files = os.listdir(root)
for f in files:
if (os.path.isdir(root + f)):
if addroot == True:
dirList.append(root + f)
else:
dirList.append(f)
if (os.path.isfile(root + f)):
if addroot == True:
fileList.append(root + f)
else:
fileList.append(f)
if type == "f":
return fileList
elif type == "d":
return dirList
else:
print("ERROR: TMC.dir(root,type) type must be [f] for file or [d] for dir")
return 0
def save_ply(points, colors, filename):
vertex = np.array([tuple(p) for p in points], dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')])
vertex_color = np.array([tuple(c) for c in colors], dtype=[('red', 'u1'), ('green', 'u1'), ('blue', 'u1')])
n = len(vertex)
assert len(vertex_color) == n
vertex_all = np.empty(n, dtype=vertex.dtype.descr + vertex_color.dtype.descr)
for prop in vertex.dtype.names:
vertex_all[prop] = vertex[prop]
for prop in vertex_color.dtype.names:
vertex_all[prop] = vertex_color[prop]
ply = plyfile.PlyData([plyfile.PlyElement.describe(vertex_all, 'vertex')], text=False)
ply.write(filename)
print("save ply to", filename)
def pc_getbbox(pc):
x = []
y = []
z = []
for pts in pc:
x.append(pts[0])
y.append(pts[1])
z.append(pts[2])
boundary = [min(x), max(x), min(y), max(y), min(z), max(z)]
return boundary
def scene2instances(scene_path, out_root, all_label, label_map, issave_ply):
print("Process Scene:", scene_path)
sceneid = scene_path.strip().split("scene")[1]
spaceid = sceneid.split("_")[0]
scanid = sceneid.split("_")[1]
label_list = all_label[0]
label_info = all_label[1]
pts_dir = out_root + "/pts/"
# check the path
if not os.path.exists(pts_dir):
print(pts_dir, "Not Exists! Create", pts_dir)
os.makedirs(pts_dir)
if save_ply:
ply_dir = out_root + "/ply/" + spaceid + scanid + "/"
if not os.path.exists(ply_dir):
print(ply_dir, "Not Exists! Create", ply_dir)
os.makedirs(ply_dir)
ply_file = scene_path + "/scene" + sceneid + "_vh_clean_2.ply"
jsonflie = scene_path + "/scene" + sceneid + "_vh_clean_2.0.010000.segs.json"
aggjsonfile = scene_path + "/scene" + sceneid + ".aggregation.json"
# Read ply file
print("\nRead ply file:", ply_file)
plydata = PlyData.read(ply_file).elements[0].data
pts_num = len(plydata)
print("points num:", pts_num)
# Read json file
print("Read json file:", jsonflie)
json_data = json.load(open(jsonflie))
# check json file
if json_data['sceneId'].strip() == ('scene' + sceneid):
segIndices = json_data['segIndices']
seg_num = len(segIndices)
# check num
if seg_num != pts_num:
print("seg num != pts num!")
os.exit(0)
else:
print("Read Wrong Json File!")
os.exit(0)
# Read aggregation json file
print("Read aggregation json file:", aggjsonfile)
aggjson_data = json.load(open(aggjsonfile))
# check json file
if aggjson_data['sceneId'].strip() == ('scene' + sceneid):
segGroups = aggjson_data['segGroups']
else:
print("Read Wrong Aggregation Json File!")
os.exit(0)
# split pts
obj_dict = {}
for k, pts in enumerate(plydata):
seg_indice = segIndices[k]
# find obj
label = "unannotated"
objid = -1
for seg in segGroups:
segments = seg['segments']
if seg_indice in segments:
label = seg['label'].strip()
objid = seg['objectId']
break
obj_key = str(label + "_" + str(objid)).strip()
if obj_key not in obj_dict.keys():
obj_dict[obj_key] = []
obj_dict[obj_key].append(pts)
# save data file by obj
for objkey in obj_dict.keys():
obj_label = objkey.split("_")[0]
obj_id = objkey.split("_")[1]
if obj_label in label_list:
label_id = label_list.index(obj_label)
else:
label_id = 0
label_full = label_info[label_id]
label_id = label_full[0]
label_s55 = label_full[3]
label_s55_id = 0
for l in label_map:
if label_s55 == l[1]:
label_s55_id = l[0]
if label_s55_id != 0:
pts_out_file = pts_dir + spaceid + scanid + "%04d" % int(obj_id) + "_" + str(label_s55_id) + ".pts"
f_pts = open(pts_out_file, "w")
pts = []
rgb = []
for p in obj_dict[objkey]:
pts.append([p[0], p[1], p[2]])
rgb.append([p[3], p[4], p[5]])
bbox = pc_getbbox(pts)
dimxy = [bbox[1] - bbox[0], bbox[3] - bbox[2]]
# retrans
for i in range(len(pts)):
pts[i] = [pts[i][0] - bbox[0] - dimxy[0] / 2, pts[i][2] - bbox[4], pts[i][1] - bbox[2] - dimxy[1] / 2]
if issave_ply:
ply_out_file = ply_dir + spaceid + "_" + scanid + "_" + "%04d" % int(
obj_id) + "_" + obj_label + "_" + str(label_id) + "_" + str(label_s55) + "_" + str(
label_s55_id) + ".ply"
seg_pts = []
seg_ply = []
for k, p in enumerate(pts):
seg_pts.append((p[0], p[1], p[2]))
seg_ply.append((rgb[k][0], rgb[k][1], rgb[k][2]))
save_ply(seg_pts, seg_ply, ply_out_file)
# write pts xyzrgb
for k, p in enumerate(pts):
f_pts.writelines(str(p[0]) + " " + str(p[1]) + " " + str(p[2]) + " " + str(rgb[k][0]) + " " + str(
rgb[k][1]) + " " + str(rgb[k][2]) + "\n")
f_pts.close()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--folder', '-f', help='Path to data folder')
parser.add_argument('--benchmark', '-b', help='Path to benchmark folder')
parser.add_argument('--outpath', '-o', help='Path to output folder')
parser.add_argument('--saveply', '-s', action='store_true', help='Save color ply or not')
args = parser.parse_args()
print(args)
label_tsv = args.benchmark + "/scannet-labels.combined.tsv"
trainval_list_file = args.benchmark + "/scannet_trainval.txt"
test_list_file = args.benchmark + "/scannet_test.txt"
label_shapenetcore55 = args.benchmark + "/classes_ObjClassification-ShapeNetCore55.txt"
##########################################################Read Source##########################################################
print("read scene dir:", args.folder)
scenedir = dir(args.folder, 'd')
print("read trainval list:", trainval_list_file)
train_scene_list = []
with open(trainval_list_file, 'r') as train_f:
for line in train_f.readlines():
sceneid = line.strip().split("scene")[1]
spaceid = sceneid.split("_")[0]
scanid = sceneid.split("_")[1]
train_scene_list.append(spaceid + scanid)
print("read test list:", test_list_file)
test_scene_list = []
with open(test_list_file, 'r') as train_f:
for line in train_f.readlines():
sceneid = line.strip().split("scene")[1]
spaceid = sceneid.split("_")[0]
scanid = sceneid.split("_")[1]
test_scene_list.append(spaceid + scanid)
print("read label tsv file:", label_tsv)
label_map = []
label_info = []
with open(label_tsv, 'r') as tsv_f:
for k, line in enumerate(tsv_f.readlines()):
if k > 0:
line_s = line.strip().split('\t')
label_id = int(line_s[0])
category = line_s[1]
count = int(line_s[2])
ShapeNetCore55 = line_s[11]
label_map.append(category)
label_info.append([label_id, category, count, ShapeNetCore55])
print("read shapenetcore55 label file:", label_shapenetcore55)
label_shapenetcore55_map = []
with open(label_shapenetcore55, 'r') as label_shapenetcore55_f:
for k, line in enumerate(label_shapenetcore55_f.readlines()):
line_s = line.strip().split('\t')
label_id = line_s[0]
category = line_s[1]
label_shapenetcore55_map.append([label_id, category])
# split scene to train and test
process_train_list = []
process_test_list = []
for scene in scenedir:
sceneid = scene.strip().split("scene")[1]
spaceid = sceneid.split("_")[0]
scanid = sceneid.split("_")[1]
scenename = spaceid + scanid
if scenename in train_scene_list:
process_train_list.append(scene)
elif scenename in test_scene_list:
process_test_list.append(scene)
print("Train all:", len(train_scene_list), "Test all:", len(test_scene_list), "Dir all:", len(scenedir))
print("Process Train:", len(process_train_list), "Process Test:", len(process_test_list))
##########################################################Process Data##########################################################
print("Process Train Scene:")
for scene in process_train_list:
scene2instances(scene, args.outpath + "/train/", [label_map, label_info], label_shapenetcore55_map,
args.saveply)
print("Process Test Scene:")
for scene in process_test_list:
scene2instances(scene, args.outpath + "/test/", [label_map, label_info], label_shapenetcore55_map, args.saveply)
if __name__ == '__main__':
main()