将图像作为Tensorflow数据加载到目录中

2024-04-26 22:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我对ML比较陌生,对TensorfFlow也很陌生。我花了很多时间在TensorFlow MINST教程以及https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/how_tos/reading_data上,试图找出如何读取自己的数据,但我有点困惑。

我有一堆图片(.png)在/images/0_Non/目录下。我试着把它们变成一个TensorFlow数据集,这样我就可以把MINST教程中的内容作为第一步运行了。

import tensorflow as tf

# Make a queue of file names including all the JPEG images files in the relative image directory.
filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once("../images/0_Non/*.png"))

image_reader = tf.WholeFileReader()

# Read a whole file from the queue, the first returned value in the tuple is the filename which we are ignoring.
_, image_file = image_reader.read(filename_queue)

image = tf.image.decode_png(image_file)

# Start a new session to show example output.
with tf.Session() as sess:
    # Required to get the filename matching to run.
    tf.initialize_all_variables().run()

    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)

我不太明白这里发生了什么。所以看起来image是张量,image_tensor是numpy数组?

如何将图像放入数据集中?我还试着按照Iris的例子,这是一个CSV,它把我带到这里:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/base.py,但不知道如何让这为我的情况下,我有一堆png的工作

谢谢!


Tags: theto数据runimagepngqueuetf
1条回答
网友
1楼 · 发布于 2024-04-26 22:20:59

最近添加的^{} API使此操作更容易:

import tensorflow as tf

# Make a Dataset of file names including all the PNG images files in
# the relative image directory.
filename_dataset = tf.data.Dataset.list_files("../images/0_Non/*.png")

# Make a Dataset of image tensors by reading and decoding the files.
image_dataset = filename_dataset.map(lambda x: tf.decode_png(tf.read_file(x)))

# NOTE: You can add additional transformations, like 
# `image_dataset.batch(BATCH_SIZE)` or `image_dataset.repeat(NUM_EPOCHS)`
# in here.

iterator = image_dataset.make_one_shot_iterator()
next_image = iterator.get_next()

# Start a new session to show example output.
with tf.Session() as sess:

  try:

    while True:
      # Get an image tensor and print its value.
      image_array = sess.run([next_image])
      print(image_tensor)

  except tf.errors.OutOfRangeError:
    # We have reached the end of `image_dataset`.
    pass

请注意,对于培训,您需要从某处获得标签。Dataset.zip()转换是将image_dataset与来自不同源的标签数据集组合在一起的可能方法。

相关问题 更多 >