/
graphcut_test_svg.py
345 lines (289 loc) · 13.3 KB
/
graphcut_test_svg.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
# Copyright (c) 2016 Byungsoo Kim. All Rights Reserved.
#
# Byungsoo Kim, ETH Zurich
# kimby@student.ethz.ch, http://byungsoo.me
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os
from os.path import basename
import time
from subprocess import call
import io
from six.moves import xrange # pylint: disable=redefined-builtin
import numpy as np
from numpy import linalg as LA
import scipy.stats
import scipy.misc
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import cairosvg
import tensorflow as tf
from linenet.linenet_manager import LinenetManager
# parameters
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('test_dir', 'test/svg',
"""Directory where to write event logs """
"""and checkpoint.""")
tf.app.flags.DEFINE_string('data_dir', 'data/svg',
"""Data directory""")
tf.app.flags.DEFINE_integer('max_num_labels', 20,
"""the maximum number of labels""")
# tf.app.flags.DEFINE_integer('label_cost', 100,
# """label cost""")
tf.app.flags.DEFINE_float('neighbor_sigma', 8,
"""neighbor sigma""")
tf.app.flags.DEFINE_float('prediction_sigma', 0.7,
"""prediction sigma""")
def _imread(img_file_name, inv=False):
""" Read, grayscale and normalize the image"""
# img = np.array(Image.open(img_file_name).convert('L')).astype(np.float) / 255.0
with open(img_file_name, 'r') as f:
# svg = f.read() or
# scale image
svg = f.readline()
id_width = svg.find('width')
id_xmlns = svg.find('xmlns', id_width)
svg_size = 'width="96" height="96" viewBox="0 0 640 480" '
svg = svg[:id_width] + svg_size + svg[id_xmlns:]
# gather normal paths and remove thick white stroke
path_list = []
while True:
svg_line = f.readline()
if not svg_line: break
# remove thick white strokes
id_white_stroke = svg_line.find('#fff')
if id_white_stroke == -1:
# gather normal paths
if svg_line.find('path t=') >= 0:
svg_line.replace('stroke-width="2"', 'stroke-width="1"')
path_list.append(svg_line)
svg = svg + svg_line
# read preprocessed svg
try:
png = cairosvg.svg2png(bytestring=svg)
except Exception as e:
# print('error %s, file %s' % (e, file_path))
svg = svg + '</svg>'
png = cairosvg.svg2png(bytestring=svg)
img = np.array(Image.open(io.BytesIO(png)))[:,:,3].astype(np.float) / 255.0
# img = scipy.stats.threshold(img, threshmax=0.1, newval=1.0)
line_pixels = np.nonzero(img)
totalnum_line_pixels = float(len(line_pixels[0]))
threshmax = np.amax(img) - 0.02
print('totalnum_line_pixels: %d, max: %f' % (totalnum_line_pixels, threshmax))
while True:
img_ = scipy.stats.threshold(img, threshmax=threshmax, newval=1.0)
line_pixels = np.nonzero(img_ > threshmax)
num_line_pixels = len(line_pixels[0])
print('num_line_pixels: %d' % num_line_pixels)
if num_line_pixels/totalnum_line_pixels > 0.7:
img = img_
break
else:
threshmax = threshmax - 0.02
if inv:
return 1.0 - img
else:
return img
# def graphcut(file_path):
def graphcut(linenet_manager, file_path):
file_name = os.path.splitext(basename(file_path))[0]
print('%s: %s, start graphcut opt.' % (datetime.now(), file_name))
img = _imread(file_path)
# # debug
# plt.imshow(img, cmap=plt.cm.gray)
# plt.show()
# # create managers
# start_time = time.time()
# print('%s: Linenet manager loading...' % datetime.now())
# linenet_manager = LinenetManager(img.shape) # h, w
# duration = time.time() - start_time
# print('%s: Linenet manager loaded (%.3f sec)' % (datetime.now(), duration))
# compute probability map of all line pixels
y_batch, line_pixels = linenet_manager.extract_all(img)
# specify neighbor weights
num_line_pixels = len(line_pixels[0])
sess = tf.InteractiveSession()
summary_writer = tf.train.SummaryWriter(os.path.join(FLAGS.test_dir, file_name), sess.graph)
# ###################################################################################
# debug: generate similarity map
pred_map_ph = tf.placeholder(dtype=tf.float32, shape=[None, img.shape[0], img.shape[1], 3])
pred_map_summary = tf.image_summary('pred_map', pred_map_ph, max_images=1)
for i in xrange(num_line_pixels):
p1 = np.array([line_pixels[0][i], line_pixels[1][i]])
pred_p1 = np.reshape(y_batch[i,:,:,:], [img.shape[0], img.shape[1]])
prediction_map = np.zeros([img.shape[0], img.shape[1], 3], dtype=np.float)
for j in xrange(num_line_pixels):
if i == j:
continue
p2 = np.array([line_pixels[0][j], line_pixels[1][j]])
pred_p2 = np.reshape(y_batch[j,:,:,:], [img.shape[0], img.shape[1]])
pred = (pred_p1[p2[0],p2[1]] + pred_p2[p1[0],p1[1]]) * 0.5
pred = np.exp(-0.5 * (1.0-pred)**2 / FLAGS.prediction_sigma**2)
if FLAGS.neighbor_sigma > 0:
d12 = LA.norm(p1-p2, 2)
spatial = np.exp(-0.5 * d12**2 / FLAGS.neighbor_sigma**2)
pred = spatial * pred
prediction_map[p2[0],p2[1]] = np.array([pred, pred, pred])
# else:
# prediction_map[p2[0],p2[1]] = np.array([0, pred, 1.0-pred])
prediction_map = prediction_map / np.amax(prediction_map)
prediction_map[p1[0],p1[1]] = np.array([1, 0, 0])
# plt.imshow(prediction_map)
# plt.show()
# save_path = os.path.join(FLAGS.test_dir, 'prediction_map_%d_%s' % (i, file_name))
# scipy.misc.imsave(save_path, prediction_map)
prediction_map = np.reshape(prediction_map, [1, img.shape[0], img.shape[1], 3])
summary_str = pred_map_summary.eval(feed_dict={pred_map_ph: prediction_map})
summary_tmp = tf.Summary()
summary_tmp.ParseFromString(summary_str)
summary_tmp.value[0].tag = 'pred_map/%04d' % i
summary_writer.add_summary(summary_tmp)
# print('Done')
# return
# ###################################################################################
pred_file_path = os.path.join(FLAGS.test_dir, file_name) + '.pred'
f = open(pred_file_path, 'w')
# info
f.write(pred_file_path + '\n')
f.write(FLAGS.data_dir + '\n')
f.write('%d\n' % FLAGS.max_num_labels)
# f.write('%d\n' % FLAGS.label_cost)
f.write('%f\n' % FLAGS.neighbor_sigma)
f.write('%f\n' % FLAGS.prediction_sigma)
f.write('%d\n' % num_line_pixels)
# support only symmetric edge weight
for i in xrange(num_line_pixels-1):
p1 = np.array([line_pixels[0][i], line_pixels[1][i]])
pred_p1 = np.reshape(y_batch[i,:,:,:], [img.shape[0], img.shape[1]])
prediction_list = []
for j in xrange(i+1, num_line_pixels):
p2 = np.array([line_pixels[0][j], line_pixels[1][j]])
pred_p2 = np.reshape(y_batch[j,:,:,:], [img.shape[0], img.shape[1]])
pred = (pred_p1[p2[0],p2[1]] + pred_p2[p1[0],p1[1]]) * 0.5
pred = np.exp(-0.5 * (1.0-pred)**2 / FLAGS.prediction_sigma**2)
if FLAGS.neighbor_sigma > 0:
d12 = LA.norm(p1-p2, 2)
spatial = np.exp(-0.5 * d12**2 / FLAGS.neighbor_sigma**2)
else:
spatial = 1.0
f.write('%d %d %f %f\n' % (i, j, pred, spatial))
f.close()
print('%s: %s, prediction computed' % (datetime.now(), file_name))
# run gco_linenet
start_time = time.time()
working_path = os.getcwd()
gco_path = os.path.join(working_path, 'gco/gco_src')
os.chdir(gco_path)
os.environ['LD_LIBRARY_PATH'] = os.getcwd()
call(['./gco_linenet', '../../' + pred_file_path])
os.chdir(working_path)
# read result
label_file_path = os.path.join(FLAGS.test_dir, file_name) + '.label'
f = open(label_file_path, 'r')
e_before = long(f.readline())
e_after = long(f.readline())
labels = np.fromstring(f.read(), dtype=np.int32, sep=' ')
f.close()
# os.remove(pred_file_path)
# os.remove(label_file_path)
duration = time.time() - start_time
print('%s: %s, labeling finished (%.3f sec)' % (datetime.now(), file_name, duration))
# graphcut opt.
num_labels = np.unique(labels).size
# print('%s: %s, label: %s' % (datetime.now(), file_name, labels))
print('%s: %s, the number of labels %d' % (datetime.now(), file_name, num_labels))
print('%s: %s, energy before optimization %d' % (datetime.now(), file_name, e_before))
print('%s: %s, energy after optimization %d' % (datetime.now(), file_name, e_after))
# write summary
num_labels_summary = tf.scalar_summary('num_lables', tf.constant(num_labels, dtype=tf.int16))
summary_writer.add_summary(num_labels_summary.eval())
# smooth_energy = tf.placeholder(dtype=tf.int32)
# label_energy = tf.placeholder(dtype=tf.int32)
# total_energy = tf.placeholder(dtype=tf.int32)
energy = tf.placeholder(dtype=tf.int64)
# smooth_energy_summary = tf.scalar_summary('smooth_energy', smooth_energy)
# label_energy_summary = tf.scalar_summary('label_energy', label_energy)
# total_energy_summary = tf.scalar_summary('total_energy', total_energy)
energy_summary = tf.scalar_summary('energy', energy)
# energy_summary = tf.merge_summary([smooth_energy_summary, label_energy_summary, total_energy_summary])
# # energy before optimization
# summary_writer.add_summary(energy_summary.eval(feed_dict={
# smooth_energy:e_before[0], label_energy:e_before[1], total_energy:e_before[2]}), 0)
# # energy after optimization
# summary_writer.add_summary(energy_summary.eval(feed_dict={
# smooth_energy:e_after[0], label_energy:e_after[1], total_energy:e_after[2]}), 1)
# energy before optimization
summary_writer.add_summary(energy_summary.eval(feed_dict={energy:e_before}), 0)
# energy after optimization
summary_writer.add_summary(energy_summary.eval(feed_dict={energy:e_after}), 1)
duration_ph = tf.placeholder(dtype=tf.float32)
duration_summary = tf.scalar_summary('duration', duration_ph)
summary_writer.add_summary(duration_summary.eval(feed_dict={duration_ph:duration}))
# save label map image
cmap = plt.get_cmap('jet')
cnorm = colors.Normalize(vmin=0, vmax=np.amax(labels))
cscalarmap = cmx.ScalarMappable(norm=cnorm, cmap=cmap)
label_map = np.ones([img.shape[0], img.shape[1], 3], dtype=np.float)
for i in xrange(num_line_pixels):
color = cscalarmap.to_rgba(labels[i])
# print(line_pixels[0][i],line_pixels[1][i],labels[i]) # ,color)
label_map[line_pixels[0][i],line_pixels[1][i]] = color[:3]
# label_map_path = os.path.join(FLAGS.test_dir, 'label_map_%s.png' % file_name)
# scipy.misc.imsave(label_map_path, label_map)
label_map_ph = tf.placeholder(dtype=tf.float32, shape=[None, img.shape[0], img.shape[1], 3])
label_map_summary = tf.image_summary('label_map', label_map_ph, max_images=1)
label_map = np.reshape(label_map, [1, img.shape[0], img.shape[1], 3])
summary_str = sess.run(label_map_summary, feed_dict={label_map_ph: label_map})
summary_tmp = tf.Summary()
summary_tmp.ParseFromString(summary_str)
summary_tmp.value[0].tag = 'label_map'
summary_writer.add_summary(summary_tmp)
def test():
# create managers
start_time = time.time()
print('%s: Linenet manager loading...' % datetime.now())
fixed_image_size = [96, 96]
linenet_manager = LinenetManager(fixed_image_size)
duration = time.time() - start_time
print('%s: Linenet manager loaded (%.3f sec)' % (datetime.now(), duration))
for root, _, files in os.walk(FLAGS.data_dir):
for file in files:
if not file.lower().endswith('svg'):
continue
file_path = os.path.join(root, file)
start_time = time.time()
# graphcut(file_path)
graphcut(linenet_manager, file_path)
duration = time.time() - start_time
print('%s: %s processed (%.3f sec)' % (datetime.now(), file, duration))
print('Done')
def main(_):
# if release mode, change current path
working_path = os.getcwd()
if not working_path.endswith('vectornet'):
working_path = os.path.join(working_path, 'vectornet')
os.chdir(working_path)
# make gco
print('%s: start to compile gco' % datetime.now())
# http://vision.csd.uwo.ca/code/
gco_path = os.path.join(working_path, 'gco/gco_src')
os.chdir(gco_path)
call(['make', 'rm'])
call(['make'])
call(['make', 'gco_linenet'])
os.chdir(working_path)
print('%s: gco compiled' % datetime.now())
# create test directory
if tf.gfile.Exists(FLAGS.test_dir):
tf.gfile.DeleteRecursively(FLAGS.test_dir)
tf.gfile.MakeDirs(FLAGS.test_dir)
# start
test()
if __name__ == '__main__':
tf.app.run()