-
Notifications
You must be signed in to change notification settings - Fork 34
/
data_utils.py
295 lines (226 loc) · 7.1 KB
/
data_utils.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
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, 'utils'))
import numpy as np
import pc_util
import scipy.misc
import string
import pickle
import plyfile
import h5py
# DATA_PATH = '/media/mikacuy/6TB_HDD/object_dataset_v1_fixed/'
def save_ply(points, filename, colors=None, normals=None):
vertex = np.core.records.fromarrays(points.transpose(), names='x, y, z', formats='f4, f4, f4')
n = len(vertex)
desc = vertex.dtype.descr
if normals is not None:
vertex_normal = np.core.records.fromarrays(normals.transpose(), names='nx, ny, nz', formats='f4, f4, f4')
assert len(vertex_normal) == n
desc = desc + vertex_normal.dtype.descr
if colors is not None:
vertex_color = np.core.records.fromarrays(colors.transpose() * 255, names='red, green, blue',
formats='u1, u1, u1')
assert len(vertex_color) == n
desc = desc + vertex_color.dtype.descr
vertex_all = np.empty(n, dtype=desc)
for prop in vertex.dtype.names:
vertex_all[prop] = vertex[prop]
if normals is not None:
for prop in vertex_normal.dtype.names:
vertex_all[prop] = vertex_normal[prop]
if colors is not None:
for prop in vertex_color.dtype.names:
vertex_all[prop] = vertex_color[prop]
ply = plyfile.PlyData([plyfile.PlyElement.describe(vertex_all, 'vertex')], text=False)
#if not os.path.exists(os.path.dirname(filename)):
# os.makedirs(os.path.dirname(filename))
ply.write(filename)
def load_pc_file(filename, suncg = False, with_bg = True):
#load bin file
# pc=np.fromfile(filename, dtype=np.float32)
pc=np.fromfile(os.path.join(DATA_PATH, filename), dtype=np.float32)
#first entry is the number of points
#then x, y, z, nx, ny, nz, r, g, b, label, nyu_label
if(suncg):
pc = pc[1:].reshape((-1,3))
else:
pc = pc[1:].reshape((-1,11))
#only use x, y, z for now
if with_bg:
pc = np.array(pc[:,0:3])
return pc
else:
##To remove backgorund points
##filter unwanted class
filtered_idx = np.intersect1d(np.intersect1d(np.where(pc[:,-1]!=0)[0],np.where(pc[:,-1]!=1)[0]), np.where(pc[:,-1]!=2)[0])
(values, counts) = np.unique(pc[filtered_idx,-1], return_counts=True)
max_ind = np.argmax(counts)
idx = np.where(pc[:,-1]==values[max_ind])[0]
pc = np.array(pc[idx,0:3])
return pc
def load_data(filename, num_points=1024, suncg_pl = False, with_bg_pl = True):
with open(filename, 'rb') as handle:
data = pickle.load(handle)
print("Data loaded.")
pcs = []
labels = []
print("With BG: "+str(with_bg_pl))
for i in range(len(data)):
entry = data[i]
filename = entry["filename"].replace('objects_bin/','')
pc = load_pc_file(filename, suncg = suncg_pl, with_bg = with_bg_pl)
label = entry['label']
if (pc.shape[0]<num_points):
continue
pcs.append(pc)
labels.append(label)
print(len(pcs))
print(len(labels))
return pcs, labels
def shuffle_points(pcs):
for pc in pcs:
np.random.shuffle(pc)
return pcs
def get_current_data(pcs, labels, num_points):
sampled = []
for pc in pcs:
if(pc.shape[0]<num_points):
# TODO repeat points
print("Points too less.")
return
else:
#faster than shuffle_points
idx = np.arange(pc.shape[0])
np.random.shuffle(idx)
sampled.append(pc[idx[:num_points],:])
sampled = np.array(sampled)
labels = np.array(labels)
#shuffle per epoch
idx = np.arange(len(labels))
np.random.shuffle(idx)
sampled = sampled[idx]
labels = labels[idx]
return sampled, labels
def normalize_data(pcs):
for pc in pcs:
#get furthest point distance then normalize
d = max(np.sum(np.abs(pc)**2,axis=-1)**(1./2))
pc /= d
# pc[:,0]/=max(abs(pc[:,0]))
# pc[:,1]/=max(abs(pc[:,1]))
# pc[:,2]/=max(abs(pc[:,2]))
return pcs
def normalize_data_multiview(pcs, num_view=5):
pcs_norm = []
for i in range(len(pcs)):
pc = []
for j in range(num_view):
pc_view = pcs[i][j, :, :]
d = max(np.sum(np.abs(pc_view)**2,axis=-1)**(1./2))
pc.append(pc_view/d)
pc = np.array(pc)
pcs_norm.append(pc)
pcs_norm = np.array(pcs_norm)
print("Normalized")
print(pcs_norm.shape)
return pcs_norm
#USE For SUNCG, to center to origin
def center_data(pcs):
for pc in pcs:
centroid = np.mean(pc, axis=0)
pc[:,0]-=centroid[0]
pc[:,1]-=centroid[1]
pc[:,2]-=centroid[2]
return pcs
##For h5 files
def get_current_data_h5(pcs, labels, num_points):
#shuffle points to sample
idx_pts = np.arange(pcs.shape[1])
np.random.shuffle(idx_pts)
sampled = pcs[:,idx_pts[:num_points],:]
#sampled = pcs[:,:num_points,:]
#shuffle point clouds per epoch
idx = np.arange(len(labels))
np.random.shuffle(idx)
sampled = sampled[idx]
labels = labels[idx]
return sampled, labels
def get_current_data_withmask_h5(pcs, labels, masks, num_points, shuffle=True):
#shuffle points to sample
idx_pts = np.arange(pcs.shape[1])
if (shuffle):
# print("Shuffled points: "+str(shuffle))
np.random.shuffle(idx_pts)
sampled = pcs[:,idx_pts[:num_points],:]
sampled_mask = masks[:,idx_pts[:num_points]]
#shuffle point clouds per epoch
idx = np.arange(len(labels))
##Shuffle order of the inputs
if (shuffle):
np.random.shuffle(idx)
sampled = sampled[idx]
sampled_mask = sampled_mask[idx]
labels = labels[idx]
return sampled, labels, sampled_mask
def get_current_data_parts_h5(pcs, labels, parts, num_points):
#shuffle points to sample
idx_pts = np.arange(pcs.shape[1])
np.random.shuffle(idx_pts)
sampled = pcs[:,idx_pts[:num_points],:]
sampled_parts = parts[:,idx_pts[:num_points]]
#shuffle point clouds per epoch
idx = np.arange(len(labels))
np.random.shuffle(idx)
sampled = sampled[idx]
sampled_parts = sampled_parts[idx]
labels = labels[idx]
return sampled, labels, sampled_parts
def get_current_data_discriminator_h5(pcs, labels, types, num_points):
#shuffle points to sample
idx_pts = np.arange(pcs.shape[1])
np.random.shuffle(idx_pts)
sampled = pcs[:,idx_pts[:num_points],:]
#shuffle point clouds per epoch
idx = np.arange(len(labels))
np.random.shuffle(idx)
sampled = sampled[idx]
sampled_types = types[idx]
labels = labels[idx]
return sampled, labels, sampled_types
def load_h5(h5_filename):
f = h5py.File(h5_filename)
data = f['data'][:]
label = f['label'][:]
return data, label
def load_withmask_h5(h5_filename):
f = h5py.File(h5_filename)
data = f['data'][:]
label = f['label'][:]
mask = f['mask'][:]
return data, label, mask
def load_discriminator_h5(h5_filename):
f = h5py.File(h5_filename)
data = f['data'][:]
label = f['label'][:]
model_type = f['type'][:]
return data, label, model_type
def load_parts_h5(h5_filename):
f = h5py.File(h5_filename)
data = f['data'][:]
label = f['label'][:]
parts = f['parts'][:]
return data, label, parts
def convert_to_binary_mask(masks):
binary_masks = []
for i in range(masks.shape[0]):
binary_mask = np.ones(masks[i].shape)
bg_idx = np.where(masks[i,:]==-1)
binary_mask[bg_idx] = 0
binary_masks.append(binary_mask)
binary_masks = np.array(binary_masks)
return binary_masks
def flip_types(types):
types = (types==0)
return types