Search code examples
imagetensorflowdirectorydecodetfrecord

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


I have a folder of images (png). I am trying to load them using tensforlow and decode the images.

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)

I am getting the error:

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)]]

How do I individually print name of each image and then the size of the image using Tensorflow.


Solution

  • I think you are getting above error because of below line:

    tf.initialize_all_variables().run()
    

    Replace it with tf.local_variables_initializer().run()

    And, use below code to print each image's name, shape and path:

    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)
    

    Sample output:

    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