-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
61 lines (51 loc) · 1.92 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
import os
import io
import matplotlib.pyplot as plt
import tensorflow as tf
tfk = tf.keras
def plot_to_image(figure):
"""Converts the matplotlib plot specified by 'figure' to a PNG image and
returns it. The supplied figure is closed and inaccessible after this call."""
# Save the plot to a PNG in memory.
buf = io.BytesIO()
plt.savefig(buf, format='png')
# Closing the figure prevents it from being displayed directly inside
# the notebook.
plt.close(figure)
buf.seek(0)
# Convert PNG buffer to TF image
image = tf.image.decode_png(buf.getvalue(), channels=4)
# Add the batch dimension
image = tf.expand_dims(image, 0)
return image
class PlotSamplesCallback(tfk.callbacks.Callback):
"""Plot `nex` reconstructed image to tensorboard."""
def __init__(self, logdir: str, nex: int=4, period: int=1):
super(PlotSamplesCallback, self).__init__()
logdir = os.path.join(logdir, 'samples')
self.file_writer = tf.summary.create_file_writer(logdir=logdir)
self.nex = nex
self.period = period
def plot_img(self, image):
fig, ax = plt.subplots(nrows=1, ncols=1)
image = (image + 1.) / 2.
if image.shape[-1] == 1:
image = tf.squeeze(image, axis=-1)
ax.imshow(image, vmin=0., vmax=1., cmap=plt.cm.Greys)
ax.axis('off')
return fig
def on_epoch_end(self, epoch, logs=None):
if (epoch + 1) % self.period == 0:
images = self.model.sample(self.nex)
imgs = []
for i in range(self.nex):
fig = self.plot_img(images[i])
imgs.append(plot_to_image(fig))
imgs = tf.concat(imgs, axis=0)
with self.file_writer.as_default():
tf.summary.image(
name='Samples',
data=imgs,
step=epoch,
max_outputs=self.nex
)