在 Tensorflow 中保存图像文件 [英] Saving image files in Tensorflow

查看:62
本文介绍了在 Tensorflow 中保存图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 Tensorflow,我有一个新手问题.

I'm just starting with Tensorflow and I have a newbie question.

我知道 Tensorflow 是关于神经网络的,但我只是从它的机制开始.我试图让它加载、调整大小、翻转和保存两个图像.应该是一个简单的操作,对,它让我从基础开始.

I know that Tensorflow is all about neural nets but I'm starting with just the mechanics of it. I'm trying to get it to load, resize, flip, and save two images. Should be a simple operation, right, and it gets me started with the basics.

这是我目前的代码:

import tensorflow as tf
import numpy as np

print("resizing images")

filenames = ['img1.png', 'img2.png' ]
filename_queue = tf.train.string_input_producer(filenames, num_epochs=1)

reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
images = tf.image.decode_png(value)

resized = tf.image.resize_images(images, 180,180, 1)
resized.set_shape([180,180,3])

flipped_images = tf.image.flip_up_down(resized)

resized_encoded = tf.image.encode_jpeg(flipped_images,name="save_me")

init = tf.initialize_all_variables()
sess = tf.Session()

with sess.as_default():
  tf.train.start_queue_runners()
  sess.run(init)

  f = open("/tmp/foo1.jpeg", "wb+")
  f.write(resized_encoded.eval())
  f.close()

  f = open("/tmp/foo2.jpeg", "wb+")
  f.write(resized_encoded.eval())
  f.close()

它工作正常,调整两个图像的大小并保存它们.但它总是以错误结束:

It works fine, resizing the two images and saving them. But it always ends with an error:

W tensorflow/core/common_runtime/executor.cc:1076] 0x7f97240e7a40
 Compute status: Out of range: Reached limit of 1

我显然做错了什么.如果我去掉 num_epochs=1,那么它就没有错误地结束了.

I'm obviously doing something wrong. If I take off the num_epochs=1, then it ends with no error.

我有几个问题:

我该如何正确执行此操作?

How do I do this correctly?

另外,如果我想从 filename_queue 一直到结尾都保留原始文件名,以便我可以使用原始名称保存它们,我该怎么做?我怎么知道我需要保存多少个文件?假设我正在通过读取目录来制作文件名列表.我尝试了很多不同的东西,但我永远不知道我是怎么知道什么时候到达终点的.

Also, if I want to preserve the original file names all the way from the filename_queue through to the end so I can save them with the original names, how do I do that? And how do I know how many files I need to save? Let's say I'm making the list of file names by reading a directory. I tried many different things but I could never find out how I know when I reach the end.

我调用 resized_encoded.eval() 两次对我来说似乎很奇怪.

It seems strange to me that I'm calling resized_encoded.eval() twice.

谢谢,我确定这是一个非常基本的问题,但我不明白这是如何工作的.

Thank you and I'm sure this is a very basic question but I'm not understanding how this works.

我创建了一个更简单的行为演示:

I created an even simpler demonstration of the behavior:

import tensorflow as tf
import numpy as np

filenames = ['file1.png', 'file2.png' ]

filename_queue = tf.train.string_input_producer(filenames, 
                        num_epochs=1, name="my_file_q")

reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
init = tf.initialize_all_variables()

sess = tf.Session()

with sess.as_default():
  print("session started")

  sess.run(init)

  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(coord=coord)

  for i in range (2):
    print(key.eval())

  coord.request_stop()
  coord.join(threads)

这给出了相同的警告.我不明白为什么.

This gives the same warning. I can't understand why.

推荐答案

这个警告是完全正常的.如 TensorFlow API

This warning is perfectly normal. As stated in the TensorFlow API

num_epochs:一个整数(可选).如果指定,string_input_producer从 string_tensor num_epochs 次之前产生每个字符串产生 OutOfRange 错误.如果没有指定,string_input_producer 可以循环遍历 string_tensor 中的字符串不限次数.

num_epochs: An integer (optional). If specified, string_input_producer produces each string from string_tensor num_epochs times before generating an OutOfRange error. If not specified, string_input_producer can cycle through the strings in string_tensor an unlimited number of times.

为什么这很重要,你可能会问.在我看来,我已将您的代码重构为更易于理解的内容.让我解释一下.

Why is this important, you may ask. I have refactored your code into something perhaps more understandable, in my opinion. Let me explain.

import tensorflow as tf
import numpy as np
import os
from PIL import Image

cur_dir = os.getcwd()
print("resizing images")
print("current directory:",cur_dir)

def modify_image(image):
    resized = tf.image.resize_images(image, 180, 180, 1)
    resized.set_shape([180,180,3])
    flipped_images = tf.image.flip_up_down(resized)
    return flipped_images

def read_image(filename_queue):
    reader = tf.WholeFileReader()
    key,value = reader.read(filename_queue)
    image = tf.image.decode_jpeg(value)
    return image

def inputs():
    filenames = ['img1.jpg', 'img2.jpg' ]
    filename_queue = tf.train.string_input_producer(filenames,num_epochs=2)
    read_input = read_image(filename_queue)
    reshaped_image = modify_image(read_input)
    return reshaped_image

with tf.Graph().as_default():
    image = inputs()
    init = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init)
    tf.train.start_queue_runners(sess=sess)
    for i in xrange(2):
        img = sess.run(image)
        img = Image.fromarray(img, "RGB")
        img.save(os.path.join(cur_dir,"foo"+str(i)+".jpeg"))

在上面的代码中,如果你明确设置 num_epochs=2,那么正如 API 所建议的那样,string_input_producer 循环遍历 string_tensor 中的字符串 2 次.由于 string_tensor 只有 2 个文件名,因此队列中填充了 4 个文件名.如果我将 for 循环更改为:

In the code above, if you explicitly put num_epochs=2, then as the API suggests, string_input_producer cycles through the strings in string_tensor 2 times. Since the string_tensor has only 2 filenames, the queue is filled with 4 filenames. If I change the for loop to be:

for i in xrange(5)

然后这会出错.但是,如果我将其保留在 4 点,那就没问题了.再举一个例子.如果我不放 num_epochs,那么按照建议,它可以无限次循环.放置:

then this will bug out. However, if I leave it at 4, then it will be fine. Take yet another example. If I do not put num_epochs, then as suggested, it can cycle through unlimited number of times. Putting:

for i in xrange(100)

因此不会出错.我希望这能回答您的问题.

thus does not bug out. I hope this answers your question.

我意识到你还有更多问题.

I realized you have more questions.

另外,如果我想一直保留原始文件名filename_queue 一直到最后,这样我就可以用原始名称,我该怎么做?我怎么知道我有多少文件需要保存吗?假设我正在通过阅读一个文件名列表目录.我尝试了很多不同的东西,但我永远找不到我怎么知道我什么时候到达终点.

Also, if I want to preserve the original file names all the way from the filename_queue through to the end so I can save them with the original names, how do I do that? And how do I know how many files I need to save? Let's say I'm making the list of file names by reading a directory. I tried many different things but I could never find out how I know when I reach the end.

如果您想保留原始文件名,那么您的方法需要返回文件名.这是下面的代码.

If you want to preserve the original file names, then your method needs to return the file name. Here's the code below.

import tensorflow as tf
import numpy as np
import os
from PIL import Image

cur_dir = os.getcwd()
print("resizing images")
print("current directory:",cur_dir)

def modify_image(image):
    resized = tf.image.resize_images(image, 180, 180, 1)
    resized.set_shape([180,180,3])
    flipped_images = tf.image.flip_up_down(resized)
    return flipped_images

def read_image(filename_queue):
    reader = tf.WholeFileReader()
    key,value = reader.read(filename_queue)
    image = tf.image.decode_jpeg(value)
    return key,image

def inputs():
    filenames = ['img1.jpg', 'img2.jpg' ]
    filename_queue = tf.train.string_input_producer(filenames)
    filename,read_input = read_image(filename_queue)
    reshaped_image = modify_image(read_input)
    return filename,reshaped_image

with tf.Graph().as_default():
    image = inputs()
    init = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init)
    tf.train.start_queue_runners(sess=sess)
    for i in xrange(10):
        filename,img = sess.run(image)
        print (filename)
        img = Image.fromarray(img, "RGB")
        img.save(os.path.join(cur_dir,"foo"+str(i)+".jpeg"))

要知道您需要保存多少个文件,您可以调用以下内容:

To know how many files you need to save, you could just call something along the lines of:

os.listdir(os.getcwd())

这会列出目录中的所有文件.检查 os.listdir 的 API 以专门过滤 JPG、PNG 文件类型.一旦你得到这个,你可以调用一个简单的长度操作并执行:

This lists all files in the directory. Check the API of os.listdir to filter specifically JPG, PNG file types. Once you get this, you can call a simple length operation and do:

for i in xrange(len(number_of_elements))

这篇关于在 Tensorflow 中保存图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆