/
utils.py
212 lines (170 loc) · 7.86 KB
/
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
import cv2
import tensorflow as tf
import numpy as np
from inspect_checkpoint import getAllVariables
#import matplotlib as mpl
#mpl.use('Agg')
#import matplotlib.pyplot as plt
#import ipdb
#-------------------------------------------------------------------------------
def initialize_uninitialized_variables(sess):
"""
Only initialize the weights that have not yet been initialized by other
means, such as importing a metagraph and a checkpoint. It's useful when
extending an existing model.
"""
uninit_vars = []
uninit_tensors = []
for var in tf.global_variables():
uninit_vars.append(var)
uninit_tensors.append(tf.is_variable_initialized(var))
uninit_bools = sess.run(uninit_tensors)
uninit = zip(uninit_bools, uninit_vars)
for init , var in uninit:
if not init:
print "Init to {}".format(var)
uninit = [var for init, var in uninit if not init]
sess.run(tf.variables_initializer(uninit))
#-------------------------------------------------------------------------------
def initialize_variables_from_ckpt(sess, ckpt_path):
"""
try to initialize var from given ckpt_path
"""
try :
gsaver = tf.train.Saver()
gsaver.restore(sess, ckpt_path)
except Exception as E:
print "Unable to apply global varbiable restorer on {} attempting per var restore".format(ckpt_path)
ckpt_vars = getAllVariables(ckpt_path)
assign_ops = []
for var in tf.global_variables():
vname = var.name.replace(":0","")
ngpu_var_name = vname.replace("gpus_loop/","")
if (vname in ckpt_vars) and var.shape == ckpt_vars[vname].shape:
assign_ops.append(tf.assign(var , ckpt_vars[vname]))
print "Found {}".format(var)
elif (ngpu_var_name in ckpt_vars) and var.shape == ckpt_vars[ngpu_var_name].shape:
assign_ops.append(tf.assign(var , ckpt_vars[ngpu_var_name]))
print "Found {}".format(var)
else:
print "failed to Find {}".format(var)
sess.run(assign_ops)
#-------------------------------------------------------------------------------
def load_data_source(data_source):
"""
Load a data source given it's name
"""
source_module = __import__('source_'+data_source)
get_source = getattr(source_module, 'get_source')
return get_source()
#-------------------------------------------------------------------------------
def drawSeg(seg, segGT):
FRAME_WIDTH = 512
FRAME_HEIGHT = 512
classesColors = [[0,0,0],[0,255,0],[255,0,0],[255,255,0],[0,0,255]]
segColor = np.zeros((FRAME_HEIGHT, FRAME_WIDTH, 3), dtype=np.uint8)
segColor[segGT[:,:,1] == 1] = classesColors[3]
segColor[seg == 1] = classesColors[1]
segColor[segGT[:,:,2] == 1] = classesColors[4]
segColor[seg == 2] = classesColors[2]
labels = ['BCG','LIV','LES','LIVgt','LESgt']
cv2.rectangle(segColor, (5,FRAME_HEIGHT-2), (45,FRAME_HEIGHT-70), (255,255,255), -1)
for shift in range(len(labels)):
cv2.putText(segColor, labels[shift], (10,FRAME_HEIGHT-(shift+1)*12), cv2.FONT_HERSHEY_SIMPLEX, 0.4, classesColors[shift], 1, cv2.LINE_AA, True)
return np.copy(segColor)
#-------------------------------------------------------------------------------
class MetricsSummary:
#---------------------------------------------------------------------------
def __init__(self, session, writer, metrics_names, num_samples):
self.session = session
self.writer = writer
self.num_samples = num_samples
self.metrics_namess = metrics_names
self.metric_values = {}
self.placeholders = {}
sess = session
summary_ops = []
for metric in self.metrics_namess:
sum_name = metric + '_metric'
ph_name = metric + '_metric_ph'
placeholder = tf.placeholder(tf.float32, name=ph_name)
summary_op = tf.summary.scalar(sum_name, placeholder)
self.metric_values[metric] = float(0)
self.placeholders[metric] = placeholder
summary_ops.append(summary_op)
self.summary_ops = tf.summary.merge(summary_ops)
#---------------------------------------------------------------------------
def add(self, values):
for idx, metric in enumerate(self.metrics_namess):
self.metric_values[metric] += values[idx]
#---------------------------------------------------------------------------
def push(self, epoch):
feed = {}
for metric in self.metrics_namess:
feed[self.placeholders[metric]] = self.metric_values[metric]/self.num_samples
summary = self.session.run(self.summary_ops, feed_dict=feed)
self.writer.add_summary(summary, epoch)
for metric in self.metrics_namess:
self.metric_values[metric] = float(0)
#-------------------------------------------------------------------------------
class ImageSummary:
#---------------------------------------------------------------------------
def __init__(self, session, writer, sample_name, restore=False):
self.session = session
self.writer = writer
sess = session
sum_name = sample_name+'_img'
ph_name = sample_name+'_img_ph'
self.img_placeholder = tf.placeholder(tf.float32, name=ph_name, shape=[None, None, None, 3])
self.img_summary_op = tf.summary.image(sum_name, self.img_placeholder, max_outputs=10)
#---------------------------------------------------------------------------
def push(self, epoch, samples):
FRAME_WIDTH = 512
FRAME_HEIGHT = 512
imgs = np.zeros((10, FRAME_HEIGHT, FRAME_WIDTH, 3))
for i, sample in enumerate(samples):
img = sample[0].astype(np.uint8)
imgRGB = np.concatenate([img[:,:,np.newaxis], img[:,:,np.newaxis], img[:,:,np.newaxis]], axis=-1)
seg = np.copy(sample[1])
segGT = np.copy(sample[2])
segColor = drawSeg(seg, segGT) #Predicted labels
alpha = 0.3
cv2.addWeighted(segColor, alpha, imgRGB, 1.-alpha, 0, imgRGB)
imgs[i] = imgRGB[::-1,:,:]
feed = {self.img_placeholder: imgs}
summary = self.session.run(self.img_summary_op, feed_dict=feed)
self.writer.add_summary(summary, epoch)
#-------------------------------------------------------------------------------
class LossSummary:
#---------------------------------------------------------------------------
def __init__(self, session, writer, sample_name, num_samples):
self.session = session
self.writer = writer
self.num_samples = num_samples
self.loss_names = ['L1']
self.loss_values = {}
self.placeholders = {}
sess = session
summary_ops = []
for loss in self.loss_names:
sum_name = sample_name+'_'+loss+'_loss'
ph_name = sample_name+'_'+loss+'_loss_ph'
placeholder = tf.placeholder(tf.float32, name=ph_name)
summary_op = tf.summary.scalar(sum_name, placeholder)
self.loss_values[loss] = float(0)
self.placeholders[loss] = placeholder
summary_ops.append(summary_op)
self.summary_ops = tf.summary.merge(summary_ops)
#---------------------------------------------------------------------------
def add(self, value):
for loss in self.loss_names:
self.loss_values[loss] += value
#---------------------------------------------------------------------------
def push(self, epoch):
feed = {}
for loss in self.loss_names:
feed[self.placeholders[loss]] = self.loss_values[loss]/self.num_samples
summary = self.session.run(self.summary_ops, feed_dict=feed)
self.writer.add_summary(summary, epoch)
for loss in self.loss_names:
self.loss_values[loss] = float(0)