-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvoxelBasedSegmentation.py
More file actions
349 lines (252 loc) · 9.53 KB
/
voxelBasedSegmentation.py
File metadata and controls
349 lines (252 loc) · 9.53 KB
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
348
349
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Voxel Based Segmentation
"""
#%% Imports
import time
from os import listdir
from os.path import exists, join
import os
import numpy as np
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KDTree
from utils.ply import write_ply, read_ply
from features_computation.descriptors import local_PCA, compute_features
import tqdm
from collections import namedtuple
from collections import defaultdict
import pandas as pd
import matplotlib.pyplot as plt
from math import sqrt, pi
import sys
#%%
path = './data_wo_ground/training/'
file = 'MiniLille1_wo_ground.ply'
training_path = path + file
print(training_path)
# Retrieve a slice the point cloud wo ground
cloud_ply = read_ply(training_path)
points = np.vstack((cloud_ply['x'], cloud_ply['y'], cloud_ply['z'])).T
labels = cloud_ply['class']
#%% Compute SVD on the point cloud
n = points.shape[0]
d = points.shape[1]
barycenter = np.mean(points, axis=0)
Q = points - barycenter
cov_mat = (1/n)*Q.T@Q
assert cov_mat.shape == (d, d)
eigenvalues, eigenvectors = np.linalg.eigh(cov_mat)
#%% Slice the point cloud
# HPO
bucket_size = 20
bucket_residual = 3
# Projection on the principal axis
scalar_product = (points-barycenter)@eigenvectors[:, 2]
hash_index = scalar_product//bucket_size
chunck_ids = np.unique(hash_index)
print('Slices identifiers: ', chunck_ids)
selected_id = int(sys.argv[1])
upper_bound = (selected_id+1)*bucket_size
lower_bound = selected_id*bucket_size
interest_indexes = np.where(hash_index==selected_id)[0]
fuzzy_indexes = np.where((scalar_product <= upper_bound+bucket_residual)*\
(scalar_product >= lower_bound-bucket_residual))[0]
# Store slice and display using CloudCompare
write_ply('./segmentation_results/slice_{}.ply'.format(selected_id),
[points[interest_indexes], labels[interest_indexes]],
['x', 'y', 'z', 'class'])
#%% Restrict the points
points = points[interest_indexes]
labels = labels[interest_indexes]
training_features = np.empty((0, 4))
training_labels = np.empty((0, ))
#%% 3.1 Voxelisation of the data
N = points.shape[0]
indexes = np.arange(N)
t0 = time.time()
print('Building KDTree...')
kd = KDTree(points, metric='minkowski')
t1 = time.time()
print('KDTree built in {} sec'.format(t1-t0))
#%% Single-Shot query for cubical voxels
radius=0.1
t0 = time.time()
neighborhoods_inner_sphere = kd.query_radius(points, r=radius)
t1 = time.time()
print('Query time for computing neighborhoods on all points: {} sec'.format(t1-t0))
t0 = time.time()
neighborhoods_outer_sphere = kd.query_radius(points, r=radius*sqrt(3))
t1 = time.time()
print('Query time for computing neighborhoods on all points: {} sec'.format(t1-t0))
#%% Cubic Voxel Assignation without replacement
N = points.shape[0]
assert neighborhoods_inner_sphere.shape[0] == N
assert neighborhoods_outer_sphere.shape[0] == N
assignated = np.array([False for i in range(N)])
assignated_voxel = np.array([-1 for i in range(N)])
rec_nbr_created_voxels = []
rec_nbr_assignated_points = []
s_voxel_features = np.empty((0, 15))
voxel_key = -1
for index in tqdm.tqdm(range(N)):
if assignated[index]:
continue
# 1/2 CUBIC VOXEL ASSIGNATION
inner_index = neighborhoods_inner_sphere[index]
outer_index = neighborhoods_outer_sphere[index]
# Compute the points in the cubic voxel
in_cubic = np.prod(points[outer_index] <= np.max(points[inner_index], axis=0), axis=1)*\
np.prod(points[outer_index] >= np.min(points[inner_index], axis=0), axis=1)
# Select the points in cubic voxels
in_cubic_index = outer_index[np.where(in_cubic)]
# Filter on assignated or not
non_assignated_in_cubic_index = in_cubic_index[~assignated[in_cubic_index]]
# Update assignated points
assignated[non_assignated_in_cubic_index] = True
# Assign voxel
voxel_key += 1
#
assignated_voxel[non_assignated_in_cubic_index] = voxel_key
rec_nbr_created_voxels.append(voxel_key+1)
rec_nbr_assignated_points.append(np.sum(assignated)/N)
# 2/2 CUBIC VOXEL FEATURES COMPUTATION
feature_row = []
feature_row = np.concatenate((feature_row, [voxel_key]))
voxel_points = points[non_assignated_in_cubic_index]
density = len(voxel_points)
feature_row = np.concatenate((feature_row, [density]))
voxel_center = 0.5*(np.max(voxel_points, axis=0) + np.min(voxel_points, axis=0))
feature_row = np.concatenate((feature_row, voxel_center))
barycenter = np.mean(voxel_points, axis=0)
feature_row = np.concatenate((feature_row, barycenter))
voxel_size = np.max(voxel_points, axis=0) - np.min(voxel_points, axis=0)
feature_row = np.concatenate((feature_row, voxel_size))
# Extract features from voxel_points
eigenvalues, eigenvectors = local_PCA(voxel_points)
normal = eigenvectors[:, 2]
verticality = 2*np.arcsin(np.abs(normal@np.array([0, 0, 1])))/pi
eps = 1e-6
linearity = 1- eigenvalues[1] / (eigenvalues[0]+eps)
planarity = (eigenvalues[1] - eigenvalues[2])/(eigenvalues[0]+eps)
sphericity = eigenvalues[2]/(eigenvalues[0]+eps)
feature_row = np.concatenate((feature_row,
[verticality, linearity, planarity, sphericity]))
s_voxel_features = np.vstack((s_voxel_features, feature_row))
print('Number of created s-voxels:', voxel_key+1)
print('Should be equal to 1:', np.mean(assignated))
#%%
fields = ['voxel_key',
'density',
'Vx', 'Vy', 'Vz',
'Bx', 'By', 'Bz',
'Sx', 'Sy', 'Sz',
'verticality', 'linearity', 'planarity', 'sphericity']
df = pd.DataFrame(s_voxel_features, columns=fields)
df.index = df['voxel_key']
df = df.drop(['voxel_key'], axis=1)
#%%
V = df[['Vx', 'Vy', 'Vz']].as_matrix()
B = df[['Bx', 'By', 'Bz']].as_matrix()
S = df[['Sx', 'Sy', 'Sz']].as_matrix()
#%% Union-Find datastructure
# https://github.com/jilljenn/tryalgo
class UnionFind:
def __init__(self, n):
self.up = list(range(n))
self.rank = [0]*n
def find(self, x):
if self.up[x] == x:
return x
else:
self.up[x] = self.find(self.up[x])
return self.up[x]
def union(self, x, y):
repr_x = self.find(x)
repr_y = self.find(y)
if repr_x == repr_y:
return False
if self.rank[repr_x] == self.rank[repr_y]:
self.rank[repr_x] += 1
self.up[repr_y] = repr_x
elif self.rank[repr_x] > self.rank[repr_y]:
self.up[repr_y] = repr_x
else:
self.up[repr_x] = repr_y
return True
#%% 3.3 Clustering by Link Chain Method
uf = UnionFind(V.shape[0])
# Build a kdtree on the voxel centers
t0 = time.time()
print('Building KDTree...')
kd = KDTree(V, metric='chebyshev')
t1 = time.time()
print('KDTree built in {} sec'.format(t1-t0))
# Define the inter voxel distance
c_d = 0.05*np.array([1, 1, 1])
# Query by majoration
neighborhoods = kd.query_radius(V, r=radius+np.max(c_d))
for index in range(V.shape[0]):
# Compute linkage bool
inter_voxel_abs_dist = np.abs(V[index]-V[neighborhoods[index]])
size_term = 0.5*(S[index]+S[neighborhoods[index]])
cells_term = c_d
# Selection of the secondary-links
is_linked = np.prod(inter_voxel_abs_dist < size_term + cells_term, axis=1)
secondary_links = neighborhoods[index][np.where(is_linked)]
for secondary_voxel in secondary_links:
uf.union(index, secondary_voxel)
#%%
from collections import Counter
count = Counter(uf.up)
segmented_objects = []
for point_index in range(points.shape[0]):
segment_id = uf.up[assignated_voxel[point_index]]
segmented_objects.append(segment_id)
segmented_objects = np.array(segmented_objects).astype('float')
high_confidence_index = []
ordered_count = count.most_common()
min_nbr_point_per_voxel = 20 # HPO
# initialize
segment_id, nbr_voxel = ordered_count[0]
i = 0
while nbr_voxel >= min_nbr_point_per_voxel:
#
point_indexes = np.where(segmented_objects==segment_id)[0]
high_confidence_index += list(point_indexes)
#
i+=1
segment_id, nbr_voxel = ordered_count[i]
print(i)
# remaining indexes are those with low confidences
low_confidence_index = set(np.arange(points.shape[0])).difference(set(high_confidence_index))
low_confidence_index = np.sort(list(low_confidence_index))
high_conf_points = points[high_confidence_index]
labels_high_conf = segmented_objects[high_confidence_index]
low_conf_points = points[low_confidence_index]
# Build KD-Tree on Known Labelled Points only
t0 = time.time()
print('Building KDTree...')
kd = KDTree(high_conf_points, metric='minkowski')
t1 = time.time()
print('KDTree built in {} sec'.format(t1-t0))
nn1 = kd.query(low_conf_points, k=1, return_distance=False)
labels_low_conf = labels_high_conf[nn1.ravel()]
output_points = np.vstack((high_conf_points, low_conf_points))
output_seg_labels = np.hstack((labels_high_conf, labels_low_conf))
assert output_points.shape[0] == len(output_seg_labels)
#%% Visualize the output point
color_dict = {}
for segment_id in np.unique(output_seg_labels):
r, g, b = np.random.random(3)
color_dict[segment_id] = [r, g, b]
segmentation_color = np.zeros((len(output_seg_labels), 3))
for segment_key in color_dict:
segmentation_color[np.where(output_seg_labels == segment_key)[0]] = color_dict[segment_key]
write_ply('./segmentation_results/segmentation_slice_{}.ply'.format(selected_id),
[output_points, segmentation_color],
['x', 'y', 'z', 'Red', 'Green', 'Blue'])