/
3dReconsTructionCNN.py
403 lines (354 loc) · 17.2 KB
/
3dReconsTructionCNN.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import glob
from itertools import chain
from keras.callbacks import EarlyStopping
from keras.engine import Input
from keras.engine import Model
from keras.engine import merge
from keras.layers import Dropout, Convolution2D, Convolution3D, Flatten, Activation, MaxPooling2D, BatchNormalization
from keras.layers.convolutional import MaxPooling3D
from keras.optimizers import Adadelta, Adamax, Adagrad, Adam, Nadam
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from skimage import io
import pandas as pd
from skimage.exposure import rescale_intensity
from sklearn import preprocessing
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers.core import Dense
import numpy as np
def load_images(directory, filetype='*.png', start=0, stop=np.inf):
filenames = glob.glob(directory + filetype)
imgs = []
for i in xrange(start, min(len(filenames), stop)):
name = filenames[i]
img = io.imread(name)
imgs.append(img)
return imgs
def show_disparity_map(map_file, width, height, im_name='distance_map.png'):
disparity_map = []
with open(map_file) as f:
content = f.readlines()
for line in content:
disparity_map.append(float(line))
disparity_map = np.asarray(disparity_map)
disparity_map = np.reshape(disparity_map, (width, height))
io.imsave(im_name, rescale_intensity(disparity_map, in_range='image', out_range='dtype'))
plt.imshow(disparity_map, cmap='Greys_r')
plt.show()
def load_gt(directory, start=0, stop=np.inf):
filenames = glob.glob(directory)
gts = []
for i in xrange(start, min(len(filenames), stop)):
name = filenames[i]
gt = []
with open(name) as f:
content = f.readlines()
for line in content:
terms = line.split()
for j in xrange(len(terms)):
terms[j] = float(terms[j])
gt.append(terms)
gts.append(gt)
return gts
def get_gt_index(frame_no):
return int(round(((frame_no / 25.0 + 0.466667) * 30))) % 20
def visualize(gt, filename):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for x, y, z in gt:
ax.scatter(x, y, z)
plt.savefig(filename)
def generate_vectors(lefts, rights, gts, offset=0, window_size=12):
data_r = []
data_l = []
data_y = []
for idx in xrange(len(lefts)):
left = rescale_intensity(lefts[idx], in_range='image', out_range='float')
right = rescale_intensity(rights[idx], in_range='image', out_range='float')
gt_idx = get_gt_index(idx + offset)
gt = gts[gt_idx]
# print gt_idx
width, height, channels = left.shape
for i in xrange(window_size,width-window_size):
for j in xrange(window_size,height-window_size):
y = gt[i + width * j]
if y == [0, 0, 0]:
continue
l = left[i-window_size:i+window_size, j-window_size:j+window_size]
r = right[i-window_size:i+window_size, j-window_size:j+window_size]
# x = (l)
# x = []
# for p, q in zip(l, r):
# x.append(p)
# x.append(q)
data_l.append(l)
data_r.append(r)
data_y.append(y)
return np.asarray(data_l, dtype=float), np.asarray(data_r, dtype=float),np.asarray(data_y, dtype=float)
def generate_training_data(left_imgs, right_imgs, gts):
l, r, y = generate_vectors(left_imgs, right_imgs, gts)
# l = preprocessing.scale(l)
# r = preprocessing.scale(r)
n_samples = len(l)
idx_rnd = np.random.permutation(n_samples)
l = l[idx_rnd]
r = r[idx_rnd]
y = y[idx_rnd]
l_train = l[0:n_samples / 2]
r_train = r[0:n_samples / 2]
y_train = y[0:n_samples / 2]
l_test = l[n_samples / 2 + 1:-1]
r_test = l[n_samples / 2 + 1:-1]
y_test = y[n_samples / 2 + 1:-1]
return (l_train,r_train, y_train), (l_test, r_test, y_test)
def train(in_shape=(24,24,3), out_shape=(1), p_reg=0.01, p_dropout=0.5):
# l_train = l_train
# r_train = r_train
# y_train = y_train
# in_neurons = len(l_train[0])
# print l_train[0].shape
# out_neurons = len(y_train[0])
hidden_neurons = 500
input_1 = Input(shape=in_shape, name='input1')
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(input_1)
# x = MaxPooling2D(pool_size=(2,2))(x)
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = BatchNormalization()(x)
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2,2))(x)
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = BatchNormalization()(x)
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2,2))(x)
x = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
# x = MaxPooling2D(pool_size=(2, 2))(x)
x = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = BatchNormalization()(x)
input_2 = Input(shape=in_shape, name='input2')
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(input_2)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
y = MaxPooling2D(pool_size=(2, 2))(y)
y = BatchNormalization()(y)
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
y = MaxPooling2D(pool_size=(2, 2))(y)
y = BatchNormalization()(y)
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(128, 5, 5, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(64, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
# y = MaxPooling2D(pool_size=(2, 2))(y)
y = Convolution2D(32, 3, 3, border_mode='same', activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(y)
y = MaxPooling2D(pool_size=(2, 2))(y)
y = BatchNormalization()(y)
z = merge([x, y], mode='concat')
z = Flatten()(z)
z = Dense(4096, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dense(4096, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dropout(p_dropout)(z)
z = Dense(2048, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dense(2048, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dropout(p_dropout)(z)
z = Dense(1024, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dense(1024, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal')(z)
z = Dropout(p_dropout)(z)
z = Dense(out_shape, activation='relu', W_regularizer=l2(p_reg),
init='glorot_normal', name='output')(z)
# l_datagen = ImageDataGenerator(zca_whitening=True)
# r_datagen = ImageDataGenerator(zca_whitening=True)
#
# l_datagen.fit(l_train)
# r_datagen.fit(r_train)
model = Model(input=[input_1, input_2], output=z)
# model = Sequential()
# model.add(Convolution3D(32, 3, 3, 3, input_shape=x_train[0].shape,border_mode='same'))
# model.add(Activation('relu'))
# model.add(MaxPooling3D(pool_size=(2,2,1)))
# model.add(Convolution3D(32, 3, 3, 3,border_mode='same'))
# model.add(Activation('relu'))
# model.add(MaxPooling3D(pool_size=(2,2,1)))
# model.add(Convolution3D(64, 3, 3, 3,border_mode='same'))
# model.add(Activation('relu'))
# model.add(MaxPooling3D(pool_size=(2,2,1),dim_ordering='th'))
# in_layer = Dense(hidden_neurons, input_dim=in_neurons, W_regularizer=l2(p_reg), activation='relu',
# init='glorot_normal')
# model.add(in_layer)
# model.add(
# Dense(hidden_neurons, input_dim=hidden_neurons, W_regularizer=l2(p_reg), activation='relu',
# init='glorot_normal'))
# model.add(Dropout(p_dropout))
# hidden_layer = Dense(hidden_neurons, input_dim=hidden_neurons, W_regularizer=l2(p_reg), activation='relu',
# init='glorot_normal')
# model.add(hidden_layer)
# drop_layer = Dropout(p_dropout)
# model.add(drop_layer)
#
# model.add(
# Dense(hidden_neurons, input_dim=hidden_neurons, W_regularizer=l2(p_reg), activation='relu',
# init='glorot_normal'))
# model.add(Dropout(p_dropout))
# hidden_layer = Dense(hidden_neurons, input_dim=hidden_neurons, W_regularizer=l2(p_reg), activation='relu',
# init='glorot_normal')
# model.add(hidden_layer)
# drop_layer = Dropout(p_dropout)
# model.add(drop_layer)
#
# model.add(Flatten())
# model.add(Dense(64))
# model.add(Activation('relu'))
# model.add(Dropout(0.5))
# model.add(Dense(out_neurons))
# model.add(Activation('relu'))
# out_layer = Dense(out_neurons, activation='sigmoid', W_regularizer=l2(p_reg),
# init='glorot_normal')
# model.add(out_layer)
opt = Adamax(lr=1e-1)
model.compile(loss="mse", optimizer=opt)
print model.summary()
# model.fit_generator(zip(l_datagen, r_datagen))
# model.save("cnn_model.h5")
return model
def generate_array_from_image(lefts, rights, gts, window_size=12, offset=0, batch_size=1000):
for idx in xrange(len(lefts)):
data_r = []
data_l = []
data_y = []
left = rescale_intensity(lefts[idx], in_range='image', out_range='float')
right = rescale_intensity(rights[idx], in_range='image', out_range='float')
gt_idx = get_gt_index(idx + offset)
gt = gts[gt_idx]
# print gt_idx
width, height, channels = left.shape
for i in xrange(window_size, width - window_size):
for j in xrange(window_size, height - window_size):
y = gt[i + width * j]
if y == [0, 0, 0]:
continue
l = left[i - window_size:i + window_size, j - window_size:j + window_size]
r = right[i - window_size:i + window_size, j - window_size:j + window_size]
# x = (l)
# x = []
# for p, q in zip(l, r):
# x.append(p)
# x.append(q)
data_l.append(l)
data_r.append(r)
data_y.append(y)
if (len(data_l) == batch_size):
yield ({'input1': np.asarray(data_l, dtype=float), 'input2': np.asarray(data_r, dtype=float)}, {'output': np.asarray(data_y, dtype=float)})
data_r = []
data_l = []
data_y = []
yield ({'input1': np.asarray(data_l, dtype=float), 'input2': np.asarray(data_r, dtype=float)},
{'output': np.asarray(data_y, dtype=float)})
def main(left_dir, right_dir, gt_dir, out_file="predicted.csv", p_batch_size=200, p_nb_epochs=1000, p_validation_split=0.05):
stop=np.inf
left_imgs = load_images(left_dir,stop=stop)
right_imgs = load_images(right_dir,stop=stop)
gts = load_gt(gt_dir)
# (l_train, r_train, y_train), (l_test, r_test, y_test) = generate_training_data(left_imgs, right_imgs, gts)
print 'training...'
early_stopping = EarlyStopping(monitor='loss', patience=2)
model = train()
model.fit_generator(generate_array_from_image(left_imgs, right_imgs, gts), samples_per_epoch=1000000,nb_epoch=p_nb_epochs, callbacks=[early_stopping])
model.save('cnn.h5')
# model.fit([l_train, r_train], y_train, batch_size=p_batch_size, nb_epoch=p_nb_epochs, validation_split=p_validation_split, shuffle=True)
# (l_train, r_train, y_train), (l_test, r_test, y_test) = generate_training_data(left_imgs, right_imgs, gts)
# predicted = model.predict([l_test, r_test])
# rmse = np.sqrt(((predicted - y_test) ** 2).mean())
# print rmse
# pd.DataFrame(predicted).to_csv(out_file, index=False)
if __name__ == "__main__":
base = '/home/balint/dev/datasets/heart/'
main(base + 'left/', base + 'right/', base + 'gt/disparityMap*')