给定一个张量流事件文件,如何提取与特定标签相对应的图像,然后以通用格式将它们保存到磁盘,例如
.png
?
您可以像这样提取图像。输出格式可能取决于摘要中图像的编码方式,因此写入磁盘的结果可能需要使用除
.png
之外的其他格式
import os
import scipy.misc
import tensorflow as tf
def save_images_from_event(fn, tag, output_dir='./'):
assert(os.path.isdir(output_dir))
image_str = tf.placeholder(tf.string)
im_tf = tf.image.decode_image(image_str)
sess = tf.InteractiveSession()
with sess.as_default():
count = 0
for e in tf.train.summary_iterator(fn):
for v in e.summary.value:
if v.tag == tag:
im = im_tf.eval({image_str: v.image.encoded_image_string})
output_fn = os.path.realpath('{}/image_{:05d}.png'.format(output_dir, count))
print("Saving '{}'".format(output_fn))
scipy.misc.imsave(output_fn, im)
count += 1
然后示例调用可能如下所示:
save_images_from_event('path/to/event/file', 'tag0')
请注意,这假设事件文件已完全写入 - 如果没有完全写入,则可能需要进行一些错误处理。
如果您使用 TensorFlow 2,这效果很好
from collections import defaultdict, namedtuple
from typing import List
import tensorflow as tf
TensorBoardImage = namedtuple("TensorBoardImage", ["topic", "image", "cnt"])
def extract_images_from_event(event_filename: str, image_tags: List[str]):
topic_counter = defaultdict(lambda: 0)
serialized_examples = tf.data.TFRecordDataset(event_filename)
for serialized_example in serialized_examples:
event = event_pb2.Event.FromString(serialized_example.numpy())
for v in event.summary.value:
if v.tag in image_tags:
if v.HasField('tensor'): # event for images using tensor field
s = v.tensor.string_val[2] # first elements are W and H
tf_img = tf.image.decode_image(s) # [H, W, C]
np_img = tf_img.numpy()
topic_counter[v.tag] += 1
cnt = topic_counter[v.tag]
tbi = TensorBoardImage(topic=v.tag, image=np_img, cnt=cnt)
yield tbi
虽然“v”有一个图像字段,但它是空的。
我用过
tf.summary.image("topic", img)
将图像添加到事件文件中。
import os
import tensorflow as tf
from tensorflow.python.framework import tensor_util
from PIL import Image
import numpy as np
def extract_images_from_event_file(event_file, output_dir):
for event in tf.compat.v1.train.summary_iterator(event_file):
for value in event.summary.value:
if value.HasField('image'):
img_path = os.path.join(output_dir, f'{value.tag}_{event.step}.webp')
if os.path.isfile(img_path): continue
img = value.image
image_data = tf.image.decode_image(img.encoded_image_string).numpy()
img_array = np.array(image_data)
img_pil = Image.fromarray(img_array)
img_pil.save(img_path, lossless=True, quality=100)
print(img_path)
if __name__ == "__main__":
output_dir = "my_project_dir"
event_file = f'{output_dir}/logs/my_tensorboard_logfile'
extract_images_from_event_file(event_file, output_dir)