-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisualize.py
411 lines (350 loc) · 18.2 KB
/
visualize.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
import keras
import numpy as np
from osgeo import gdal
import cv2
from keras.models import *
from keras.layers import *
from keras.optimizers import *
import glob
import matplotlib.pyplot as plt
from keras import backend as K
from keras.preprocessing.image import *
from keras.callbacks import *
from keras import regularizers
import tensorflow as tf
import matplotlib.pyplot as plt
from evaluate import classes, convert_to_binary, compare
def unet(pretrained_weights = None,input_size = (64,64,4)):
inputs = keras.layers.Input(input_size)
noise=keras.layers.GaussianNoise(0.1)(inputs)
conv1 = keras.layers.Conv2D(64, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(noise)
conv1 = keras.layers.BatchNormalization()(conv1)
conv1 = keras.layers.Conv2D(64, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv1)
conv1 = keras.layers.BatchNormalization()(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
#32x32x32
conv2 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = BatchNormalization()(conv2)
conv2 = Conv2D(128, 3, activation = 'elu' ,padding = 'same', kernel_initializer = 'he_normal')(conv2)
conv2 = BatchNormalization()(conv2)
conv2 = Conv2D(128,3,activation = 'elu', padding = 'same',kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv2)
conv2 = BatchNormalization()(conv2)
conv2 = Conv2D(128,3,activation = 'elu', padding = 'same',kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv2)
conv2 = BatchNormalization()(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
#64x16x16
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool2)
conv3 = BatchNormalization()(conv3)
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
conv3 = BatchNormalization()(conv3)
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
conv3 = BatchNormalization()(conv3)
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
conv3 = BatchNormalization()(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
#128x8x8
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool3)
conv4 = BatchNormalization()(conv4)
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool3)
conv4 = BatchNormalization()(conv4)
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
conv4 = BatchNormalization()(conv4)
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
conv4 = BatchNormalization()(conv4)
#512x16x16
up6 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv4))
merge6 = concatenate([conv3,up6], axis = 3)
conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(merge6)
conv6 = BatchNormalization()(conv6)
conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv6)
conv6 = BatchNormalization()(conv6)
conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv6)
conv6 = BatchNormalization()(conv6)
#256x32x32
up7 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv6))
merge7 = concatenate([conv2,up7], axis = 3)
conv7 = Conv2D(128, 3, activation ='elu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
conv7 = BatchNormalization()(conv7)
conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
conv7 = BatchNormalization()(conv7)
conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
conv7 = BatchNormalization()(conv7)
conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
conv7 = BatchNormalization()(conv7)
#64x64
up8 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv7))
merge8 = concatenate([conv1,up8], axis = 3)
conv8 = Conv2D(64, 3, activation = 'elu' , padding = 'same', kernel_initializer = 'he_normal')(merge8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(64, 3, activation = 'elu' , padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(1, 3, activation = 'sigmoid', padding = 'same', kernel_initializer = 'he_normal')(conv8)
model = keras.models.Model(inputs = inputs, outputs = conv8)
if(pretrained_weights):
model.load_weights(pretrained_weights)
return model
def shallowunet(pretrained_weights = None,input_size = (64,64,4)):
inputs = keras.layers.Input(input_size)
noise=keras.layers.GaussianNoise(0.1)(inputs)
conv1 = keras.layers.Conv2D(64, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(noise)
#conv1 = keras.layers.BatchNormalization()(conv1)
#conv1 = keras.layers.Conv2D(64, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv1)
conv1 = keras.layers.BatchNormalization()(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
#32x32x32
conv2 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = BatchNormalization()(conv2)
conv2 = Conv2D(128, 3, activation = 'elu' ,padding = 'same', kernel_initializer = 'he_normal')(conv2)
conv2 = BatchNormalization()(conv2)
conv2 = Conv2D(128,3,activation = 'elu', padding = 'same',kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv2)
conv2 = BatchNormalization()(conv2)
#conv2 = Conv2D(128,3,activation = 'elu', padding = 'same',kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv2)
#conv2 = BatchNormalization()(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
#64x16x16
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool2)
conv3 = BatchNormalization()(conv3)
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
conv3 = BatchNormalization()(conv3)
conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
conv3 = BatchNormalization()(conv3)
#conv3 = Conv2D(256, 3,activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv3)
#conv3 = BatchNormalization()(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
#128x8x8
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool3)
conv4 = BatchNormalization()(conv4)
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(pool3)
conv4 = BatchNormalization()(conv4)
conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
conv4 = BatchNormalization()(conv4)
#conv4 = Conv2D(512, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
#conv4 = BatchNormalization()(conv4)
#512x16x16
up6 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv4))
merge6 = concatenate([conv3,up6], axis = 3)
conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(merge6)
conv6 = BatchNormalization()(conv6)
conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv6)
conv6 = BatchNormalization()(conv6)
#conv6 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv6)
#conv6 = BatchNormalization()(conv6)
#256x32x32
up7 = Conv2D(256, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv6))
merge7 = concatenate([conv2,up7], axis = 3)
conv7 = Conv2D(128, 3, activation ='elu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
conv7 = BatchNormalization()(conv7)
conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
conv7 = BatchNormalization()(conv7)
conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
#conv7 = BatchNormalization()(conv7)
#conv7 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal')(conv7)
conv7 = BatchNormalization()(conv7)
#64x64
up8 = Conv2D(128, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(UpSampling2D(size = (2,2))(conv7))
merge8 = concatenate([conv1,up8], axis = 3)
conv8 = Conv2D(64, 3, activation = 'elu' , padding = 'same', kernel_initializer = 'he_normal')(merge8)
conv8 = BatchNormalization()(conv8)
#conv8 = Conv2D(64, 3, activation = 'elu' , padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
#conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
#conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
#conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(32, 3, activation = 'elu', padding = 'same', kernel_initializer = 'he_normal',kernel_regularizer=regularizers.l2(0.01))(conv8)
conv8 = BatchNormalization()(conv8)
conv8 = Conv2D(1, 3, activation = 'sigmoid', padding = 'same', kernel_initializer = 'he_normal')(conv8)
model = keras.models.Model(inputs = inputs, outputs = conv8)
model.summary()
if(pretrained_weights):
model.load_weights(pretrained_weights)
return model
def image_seg( img, crop_shape,stride,model ):
'''Function that cuts image into out_shape shaped sub-images
and reflect pads excess bits'''
img_original = np.array(img)
out_shape = crop_shape
img_shape = img_original.shape
img = np.pad(img, ((0,out_shape[0]),(0,out_shape[1]),(0,0)),'reflect')
x_limit = img_shape[0]/stride
y_limit = img_shape[1]/stride
if x_limit != int(x_limit):
x_limit = int(x_limit) + 1
else:
x_limit = int( x_limit )
if y_limit != int(y_limit):
y_limit = int(y_limit) + 1
else:
y_limit = int( y_limit)
segmented = np.zeros( (img_shape[0]+out_shape[0], img_shape[1]+out_shape[1],1) )
for x_ind in range(x_limit):
for y_ind in range(y_limit):
x_t = x_ind*stride
y_t = y_ind*stride
crop = img[ x_t: x_t + out_shape[0],y_t: y_t + out_shape[1],:]
out=model.predict(np.expand_dims(crop,axis=0))
segmented[ x_t: x_t+out_shape[0] , y_t:y_t +out_shape[1]] = np.maximum(segmented[ x_t: x_t+out_shape[0] , y_t:y_t +out_shape[1]] ,out[0])
segmented = segmented[ :img_shape[0], :img_shape[1]]
segmented=cv2.GaussianBlur(segmented,(5,5),1)
kernel=np.ones((5,5),np.uint8)
#segmented=cv2.morphologyEx(segmented,cv2.MORPH_OPEN,kernel)
# ret,segmented=cv2.threshold(segmented,0.68,1,cv2.THRESH_BINARY)
# kernel=np.ones((5,5))
# segmented=cv2.morphologyEx(segmented,kernel,cv2.MORP)
# cv2.imshow('predicted',segmented )
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return segmented
def tiff_to_np(filename,n=4):
''' Converts the tif file into a numpy array '''
ds = gdal.Open(filename, gdal.GA_ReadOnly)
arys=[]
for i in range(1, ds.RasterCount+1):
arys.append(ds.GetRasterBand(i).ReadAsArray())
arys = np.asarray(arys)
print(arys.shape)
w = arys.shape[1]
h = arys.shape[2]
img = np.zeros((w,h,n))
img[:,:,0] = arys[0,:,:]/255.0
img[:,:,1] = arys[1,:,:]/255.0
img[:,:,2] = arys[2,:,:]/255.0
if n==4 :
img[:,:,3]=arys[3,:,:]/255.0
return img
def equalize2(img,n=4):
'''' Function for histogram equalization. The channel number can be varied for 4-channel or 3 -channel images '''
equ = np.zeros(img.shape)
x = np.zeros(img[:,:,0].shape)
x = img[:,:,0]
x=np.uint8(cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX))
equ[:,:,0] = cv2.equalizeHist(x)
x = img[:,:,1]
x=np.uint8(cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX))
equ[:,:,1] = cv2.equalizeHist(x)
x = img[:,:,2]
x=np.uint8(cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX))
equ[:,:,2] = cv2.equalizeHist(x)
equ = equ/255.0
if n==4:
equ[:,:,3]=img[:,:,3]/255.0
return equ
def convert_to_labels(img):
''' '''
dims=np.shape(img)
result=np.zeros((dims[0],dims[1],3))
result=cv2.normalize(result,None,0,255,cv2.NORM_MINMAX)
for i in range(dims[0]):
for j in range(dims[1]):
ind=np.argmax(img[i,j])
#print(ind)
if ind==0:
result[i,j]=np.array([0,255,0])
if ind==1:
result[i,j]=np.array([0,0,0])
if ind==2:
result[i,j]=np.array([255,255,0])
if ind==3:
result[i,j]=np.array([150,80,0])
if ind==4:
result[i,j]=np.array([255,255,255])
return result
#hardrail2 is with threshold 15
#hardrail is threshold 1
#roadweighted was done with pos_weight=1.5
#roadweighted2 pos_weight=1.25
def metric_eval(i,mode,model_name,model_weight,thresh,stride,index):
"""Funtion that evaluates a metric for the given image """
x=tiff_to_np("./The-Eye-in-the-Sky-dataset/sat/%d.tif"%i)
model=model_name(model_weight)
x=equalize2(x)
gt = tiff_to_np("./The-Eye-in-the-Sky-dataset/gt/%d.tif"%i,3)
#print(gt.shape,gt.dtype)
gt=np.uint8(gt*255)
y_pred = image_seg(x,(64,64),stride,model)
#print(y_pred.shape)
y_pred = np.uint8(y_pred>thresh)
#plt.imshow(y_pred,cmap='gray')
#plt.show()
print(compare(mode,y_pred,gt,index))
def visualize(model_name,model_weight_name,train_mode,thresh,stride,index):
"""
Function that can evaluate metrics on train data and visualize on test.
model_name : unet (54 layers)
shallowunet (38 layers)
model_weight_name : name of the weight file
train_mode : 0 - visualize test
1 - visualize and evaluate metrics on train data
thresh - threshold for evaluating metric/visualizing test
stride - the image is broken into 64 x64 patches with this stride. stride helps in getting more continuous outputs
index : index for encoding the label matrix .Depends on class as :
grass 0
trees 1
railways 2
buildings 3
roads 4
bare soil 5
oceans 6
swimming pool 7
"""
model_weight=str('./model_{}.h5'.format(model_weight_name))
model=model_name(pretrained_weights=model_weight)
if train_mode == 0: #test
num = 6
for i in range(num):
i+=1
x=tiff_to_np('./The-Eye-in-the-Sky-test-data/sat_test/%d.tif'%i)
#label=tiff_to_np('./The-Eye-in-the-Sky-dataset/gt/%d.tif'%i,n=3)
print(np.shape(x))
x= equalize2(x)
#label=np.uint8(label*255)
y=image_seg(x,(64,64),stride,model)
print("What is Y :",np.shape(y))
y=np.uint8(y*255)
x=x[:,:,:3]
ret,y = cv2.threshold(y,np.uint8(thresh*255),255,cv2.THRESH_BINARY)
#print(np.max(y), np.max(label))
#plt.subplot(131)
#plt.imshow(label)
#print(compare(1,y,label,index))
plt.subplot(121)
plt.imshow(x[:,:,::-1])
plt.subplot(122)
plt.imshow(np.squeeze(y),cmap='gray')
plt.show()
if train_mode == 1:
num = 14
for i in range(num):
i+=1
x=tiff_to_np('./The-Eye-in-the-Sky-dataset/sat/%d.tif'%i)
label=tiff_to_np('./The-Eye-in-the-Sky-dataset/gt/%d.tif'%i,n=3)
print(np.shape(x))
x= equalize2(x)
label=np.uint8(label*255)
y=image_seg(x,(64,64),stride,model)
#print(np.shape(y))
y=np.uint8(y*255)
x=x[:,:,:3]
#ret,y = cv2.threshold(y,np.uint8(thresh*255),255,cv2.THRESH_BINARY)
print(np.max(y), np.max(label))
metric_eval(i,1,model_name,model_weight,thresh,stride,index)
#plt.subplot(131)
#plt.imshow(label)
#print(compare(1,y,label,index))
plt.subplot(121)
plt.imshow(label)
plt.subplot(122)
plt.imshow(np.squeeze(y),cmap='gray')
# plt.show()
print(np.shape(y))
np.save('./outputs/%s/%d-stitched'%(model_weight_name,i),y)
print("saved")
#cv2.waitKey(0) & 0xFF
#cv2.destroyAllWindows()
visualize(unet,'ckpt_file',1,0.6,32,3)