使用tensorflow从文件夹中加载png文件并在解码前打印每个图像的名称

Load png files from a folder using tensorflow and print name of each image before decoding

我有一个图像文件夹 (png)。我正在尝试使用 tensforlow 加载它们并解码图像。

import tensorflow as tf


filename_queue = tf.train.string_input_producer(
tf.train.match_filenames_once("/Users/cf/*.png"))


image_reader = tf.WholeFileReader()


_, image_file = image_reader.read(filename_queue)


image = tf.image.decode_jpeg(image_file)

with tf.Session() as sess:
    tf.initialize_all_variables().run()

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

    image_tensor = sess.run([image])

    print(image_tensor)

    coord.request_stop()
    coord.join(threads)

我收到错误:

INFO:tensorflow:Error reported to Coordinator: <class . 
  'tensorflow.python.framework.errors_impl.FailedPreconditionError'>, 
    Attempting to use uninitialized value matching_filenames_1
         [[{{node matching_filenames_1/read}} = 
    Identity[T=DT_STRING, 
    _device="/job:localhost/replica:0/task:0/device:CPU:0"] . 
  (matching_filenames_1)]]

如何使用 Tensorflow 单独打印每个图像的名称,然后打印图像的大小。

我认为您遇到上述错误是因为以下行:

tf.initialize_all_variables().run()

替换为tf.local_variables_initializer().run()

然后,使用下面的代码打印每个图像的名称、形状和路径:

all_images_paths = tf.train.match_filenames_once("./data/test/green/*.jpg")

filename_queue = tf.train.string_input_producer(all_images_paths)

image_reader = tf.WholeFileReader()
key, image_file = image_reader.read(filename_queue)

image = tf.image.decode_jpeg(image_file)

with tf.Session() as sess:
    sess.run(tf.local_variables_initializer())

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

    img_paths = sess.run(all_images_paths)
    # get number of images in the folder
    n_images = len(img_paths)

    # loop through all images 
    for i in range(n_images):
        imgf, k, img = sess.run([image_file, key, image])
        image_name = k.decode("utf-8").split('\')[-1]
        # print image name, shape and path
        print(image_name, img.shape, k.decode("utf-8"))

    coord.request_stop()
    coord.join(threads)

示例输出:

image_06741.jpg (654, 500, 3) .\data\test\green\image_06741.jpg
image_06773.jpg (500, 606, 3) .\data\test\green\image_06773.jpg
image_06751.jpg (500, 666, 3) .\data\test\green\image_06751.jpg