-
Notifications
You must be signed in to change notification settings - Fork 6
/
test_pgn.py
272 lines (227 loc) · 12.1 KB
/
test_pgn.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
"""
Generate human parsing maps/segmentation in CIHP_PGN format for any images, without labels/edges.
"""
from __future__ import print_function
from utils import *
from PIL import Image
import numpy as np
import tensorflow as tf
import argparse
from datetime import datetime
import os
import sys
import time
import scipy.misc
import scipy.io as sio
import cv2
from glob import glob
# set number of available GPUs, leave blank for CPU, otherwise 0/0,1/0,1,2/0,1,2,3
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
N_CLASSES = 20 # Total number of CIHP class labels including background
DATA_DIR = './datasets/CIHP' # dataset folder
# Get number to images in the folder
image_dir = None
if os.path.exists(os.path.join(DATA_DIR, "image/")): # see if there's a folder named "inside" the directory
image_dir = os.path.join(DATA_DIR, "image/")
else:
image_dir = DATA_DIR # otherwise take the data directory as the image folder
image_list = os.listdir(image_dir)
NUM_IMAGES = len(image_list)
# LIST_PATH = './datasets/CIHP/list/val.txt' # No need for now
# DATA_ID_LIST = './datasets/CIHP/list/val_id.txt' # No need for now
# with open(DATA_ID_LIST, 'r') as f:
# NUM_IMAGES = len(f.readlines())
RESTORE_FROM = './checkpoint/CIHP_pgn'
def main():
"""Create the model and start the evaluation process."""
# Create queue coordinator.
coord = tf.train.Coordinator()
# Load reader.
with tf.name_scope("create_inputs"):
# reader = ImageReader(DATA_DIR, LIST_PATH, DATA_ID_LIST, None, False, False, False, coord)
reader = ImageReader(DATA_DIR, None, None, None,
False, False, False, coord)
# image, label, edge_gt = reader.image, reader.label, reader.edge # label/edges are not needed, enable if you want to evaluate
image, label = reader.image, reader.label
image_rev = tf.reverse(image, tf.stack([1]))
image_list = reader.image_list
image_batch = tf.stack([image, image_rev])
# label_batch = tf.expand_dims(label, dim=0) # Add one batch dimension.
# edge_gt_batch = tf.expand_dims(edge_gt, dim=0)
h_orig, w_orig = tf.to_float(
tf.shape(image_batch)[1]), tf.to_float(tf.shape(image_batch)[2])
image_batch050 = tf.image.resize_images(image_batch, tf.stack(
[tf.to_int32(tf.multiply(h_orig, 0.50)), tf.to_int32(tf.multiply(w_orig, 0.50))]))
image_batch075 = tf.image.resize_images(image_batch, tf.stack(
[tf.to_int32(tf.multiply(h_orig, 0.75)), tf.to_int32(tf.multiply(w_orig, 0.75))]))
image_batch125 = tf.image.resize_images(image_batch, tf.stack(
[tf.to_int32(tf.multiply(h_orig, 1.25)), tf.to_int32(tf.multiply(w_orig, 1.25))]))
image_batch150 = tf.image.resize_images(image_batch, tf.stack(
[tf.to_int32(tf.multiply(h_orig, 1.50)), tf.to_int32(tf.multiply(w_orig, 1.50))]))
image_batch175 = tf.image.resize_images(image_batch, tf.stack(
[tf.to_int32(tf.multiply(h_orig, 1.75)), tf.to_int32(tf.multiply(w_orig, 1.75))]))
# Create network.
with tf.variable_scope('', reuse=False):
net_100 = PGNModel({'data': image_batch},
is_training=False, n_classes=N_CLASSES)
with tf.variable_scope('', reuse=True):
net_050 = PGNModel({'data': image_batch050},
is_training=False, n_classes=N_CLASSES)
with tf.variable_scope('', reuse=True):
net_075 = PGNModel({'data': image_batch075},
is_training=False, n_classes=N_CLASSES)
with tf.variable_scope('', reuse=True):
net_125 = PGNModel({'data': image_batch125},
is_training=False, n_classes=N_CLASSES)
with tf.variable_scope('', reuse=True):
net_150 = PGNModel({'data': image_batch150},
is_training=False, n_classes=N_CLASSES)
with tf.variable_scope('', reuse=True):
net_175 = PGNModel({'data': image_batch175},
is_training=False, n_classes=N_CLASSES)
# parsing net
parsing_out1_050 = net_050.layers['parsing_fc']
parsing_out1_075 = net_075.layers['parsing_fc']
parsing_out1_100 = net_100.layers['parsing_fc']
parsing_out1_125 = net_125.layers['parsing_fc']
parsing_out1_150 = net_150.layers['parsing_fc']
parsing_out1_175 = net_175.layers['parsing_fc']
parsing_out2_050 = net_050.layers['parsing_rf_fc']
parsing_out2_075 = net_075.layers['parsing_rf_fc']
parsing_out2_100 = net_100.layers['parsing_rf_fc']
parsing_out2_125 = net_125.layers['parsing_rf_fc']
parsing_out2_150 = net_150.layers['parsing_rf_fc']
parsing_out2_175 = net_175.layers['parsing_rf_fc']
# edge net
# edge_out2_100 = net_100.layers['edge_rf_fc']
# edge_out2_125 = net_125.layers['edge_rf_fc']
# edge_out2_150 = net_150.layers['edge_rf_fc']
# edge_out2_175 = net_175.layers['edge_rf_fc']
# combine resize
parsing_out1 = tf.reduce_mean(tf.stack([tf.image.resize_images(parsing_out1_050, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out1_075, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out1_100, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out1_125, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out1_150, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(parsing_out1_175, tf.shape(image_batch)[1:3, ])]), axis=0)
parsing_out2 = tf.reduce_mean(tf.stack([tf.image.resize_images(parsing_out2_050, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out2_075, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out2_100, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out2_125, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(
parsing_out2_150, tf.shape(image_batch)[1:3, ]),
tf.image.resize_images(parsing_out2_175, tf.shape(image_batch)[1:3, ])]), axis=0)
# edge_out2_100 = tf.image.resize_images(edge_out2_100, tf.shape(image_batch)[1:3,])
# edge_out2_125 = tf.image.resize_images(edge_out2_125, tf.shape(image_batch)[1:3,])
# edge_out2_150 = tf.image.resize_images(edge_out2_150, tf.shape(image_batch)[1:3,])
# edge_out2_175 = tf.image.resize_images(edge_out2_175, tf.shape(image_batch)[1:3,])
# edge_out2 = tf.reduce_mean(tf.stack([edge_out2_100, edge_out2_125, edge_out2_150, edge_out2_175]), axis=0)
raw_output = tf.reduce_mean(tf.stack([parsing_out1, parsing_out2]), axis=0)
head_output, tail_output = tf.unstack(raw_output, num=2, axis=0)
tail_list = tf.unstack(tail_output, num=20, axis=2)
tail_list_rev = [None] * 20
# for xx in xrange(14):
for xx in range(14):
tail_list_rev[xx] = tail_list[xx]
tail_list_rev[14] = tail_list[15]
tail_list_rev[15] = tail_list[14]
tail_list_rev[16] = tail_list[17]
tail_list_rev[17] = tail_list[16]
tail_list_rev[18] = tail_list[19]
tail_list_rev[19] = tail_list[18]
tail_output_rev = tf.stack(tail_list_rev, axis=2)
tail_output_rev = tf.reverse(tail_output_rev, tf.stack([1]))
raw_output_all = tf.reduce_mean(
tf.stack([head_output, tail_output_rev]), axis=0)
raw_output_all = tf.expand_dims(raw_output_all, dim=0)
pred_scores = tf.reduce_max(raw_output_all, axis=3)
raw_output_all = tf.argmax(raw_output_all, axis=3)
pred_all = tf.expand_dims(raw_output_all, dim=3) # Create 4-d tensor.
# raw_edge = tf.reduce_mean(tf.stack([edge_out2]), axis=0)
# head_output, tail_output = tf.unstack(raw_edge, num=2, axis=0)
# tail_output_rev = tf.reverse(tail_output, tf.stack([1]))
# raw_edge_all = tf.reduce_mean(tf.stack([head_output, tail_output_rev]), axis=0)
# raw_edge_all = tf.expand_dims(raw_edge_all, dim=0)
# pred_edge = tf.sigmoid(raw_edge_all)
# res_edge = tf.cast(tf.greater(pred_edge, 0.5), tf.int32)
# prepare ground truth
preds = tf.reshape(pred_all, [-1, ])
# gt = tf.reshape(label_batch, [-1,])
# weights = tf.cast(tf.less_equal(gt, N_CLASSES - 1), tf.int32) # Ignoring all labels greater than or equal to n_classes.
# mIoU, update_op_iou = tf.contrib.metrics.streaming_mean_iou(preds, gt, num_classes=N_CLASSES, weights=weights)
# macc, update_op_acc = tf.contrib.metrics.streaming_accuracy(preds, gt, weights=weights)
# precision and recall
# recall, update_op_recall = tf.contrib.metrics.streaming_recall(res_edge, edge_gt_batch)
# precision, update_op_precision = tf.contrib.metrics.streaming_precision(res_edge, edge_gt_batch)
# update_op = tf.group(update_op_iou, update_op_acc, update_op_recall, update_op_precision)
# update_op = tf.group(update_op_iou, update_op_acc)
# Which variables to load.
restore_var = tf.global_variables()
# Set up tf session and initialize variables.
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
init = tf.global_variables_initializer()
sess.run(init)
sess.run(tf.local_variables_initializer())
# Load weights.
loader = tf.train.Saver(var_list=restore_var)
if RESTORE_FROM is not None:
if load(loader, sess, RESTORE_FROM):
print(" [*] Load SUCCESS")
else:
print(" [!] Load failed...")
# Start queue threads.
threads = tf.train.start_queue_runners(coord=coord, sess=sess)
# evaluate prosessing
parsing_dir = './output/image_parse_pgn'
if not os.path.exists(parsing_dir):
os.makedirs(parsing_dir)
parsing_vis_dir = './output/image_parse_vis_pgn'
if not os.path.exists(parsing_vis_dir):
os.makedirs(parsing_vis_dir)
parsing_mat_dir = './output/image_parse_mat_pgn'
if not os.path.exists(parsing_mat_dir):
os.makedirs(parsing_mat_dir)
# edge_dir = './output/cihp_edge_maps' # not needed for now
# if not os.path.exists(edge_dir):
# os.makedirs(edge_dir)
# Iterate over training steps.
for step in range(NUM_IMAGES):
# parsing_, scores, edge_, _ = sess.run([pred_all, pred_scores, pred_edge, update_op])
# parsing_, scores, _ = sess.run([pred_all, pred_scores, update_op])
parsing_, scores = sess.run([pred_all, pred_scores])
if step % 100 == 0:
print('step {:d}'.format(step))
print(image_list[step])
img_split = image_list[step].split('/')
img_id = img_split[-1][:-4]
# save predicted segmentation images/parsing maps with visualized maps
msk = decode_labels(parsing_, num_classes=N_CLASSES)
parsing_im = Image.fromarray(msk[0])
parsing_im.save('{}/{}_vis.png'.format(parsing_vis_dir, img_id))
cv2.imwrite('{}/{}.png'.format(parsing_dir, img_id),
parsing_[0, :, :, 0])
sio.savemat('{}/{}.mat'.format(parsing_mat_dir, img_id),
{'data': scores[0, :, :]})
# cv2.imwrite('{}/{}.png'.format(edge_dir, img_id), edge_[0,:,:,0] * 255) # Not needed for now
res_mIou = mIoU.eval(session=sess)
res_macc = macc.eval(session=sess)
res_recall = recall.eval(session=sess)
res_precision = precision.eval(session=sess)
f1 = 2 * res_precision * res_recall / (res_precision + res_recall)
print('Mean IoU: {:.4f}, Mean Acc: {:.4f}'.format(res_mIou, res_macc))
print('Recall: {:.4f}, Precision: {:.4f}, F1 score: {:.4f}'.format(
res_recall, res_precision, f1))
coord.request_stop()
coord.join(threads)
if __name__ == '__main__':
main()
# 333