首页 > 解决方案 > 如何将张量保存为图像?

问题描述

我想将张量保存为特定文件夹中的图像。我正在使用 tf.write() 但我不知道它将图像保存在哪里。请告诉我如何将其保存为 jpeg 图像

path = "C:/Users/waqas/Desktop/0"
dirs = os.listdir( path )
for file in dirs:
    img = flip_images(file)
    img2 = tf.image.convert_image_dtype(img, tf.uint8,saturate=True)
    enc = tf.image.encode_png(img2)
    file_name = tf.constant(file)
    files = tf.write_file(file_name, enc)

标签: pythontensorflowdeep-learning

解决方案


使用以下代码:

import tensorflow as tf
import os
from PIL import Image

path = "D:\\data\\"
new_path = "D:\\new_folder\\"

filenames = os.listdir(path)
filenames = [path+images for images in filenames]
no_of_files = len(filenames)

filename_queue = tf.train.string_input_producer(filenames, num_epochs=no_of_files)
reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
image = tf.image.decode_jpeg(value)
reshaped_image = tf.image.flip_left_right(image)

with tf.Session() as sess:
    init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
    sess.run(init)
    tf.train.start_queue_runners()

    for i in range(no_of_files):
        img = sess.run(reshaped_image)
        img = Image.fromarray(img)
        img.save(os.path.join(new_path+str(i)+".jpeg"))

推荐阅读