how can i load a directory of png in tensorflow?

2019-08-19 16:23发布

i have a directory of png files . there is a train folder and test folder . In the train folder i have 10 folders as 10 labels [ 0 -9 ] .Each folder contains png files of that label . I want to load them in tensor flow for training . I am new in tensor flow i am having a very hard time getting this done

i am using anaconda ( py ver 3.5 )

import tensorflow as tf


filename_queue = tf.train.string_input_producer(
    tf.train.match_filenames_once("./images/*.jpg"))

image_reader = tf.WholeFileReader()

i have tried using this but can make it work . it only loads 1 image

1条回答
Emotional °昔
2楼-- · 2019-08-19 16:54

It's working for me though. Can you run this script ? (Updated to get Labels as well)

import tensorflow as tf
filename_queue = tf.train.string_input_producer(
tf.train.match_filenames_once("/home/xxx/Desktop/stackoverflow/images/*/*.png"))

image_reader = tf.WholeFileReader()
key, image_file = image_reader.read(filename_queue)
S = tf.string_split([key],'/')
length = tf.cast(S.dense_shape[1],tf.int32)
# adjust constant value corresponding to your paths if you face issues. It should work for above format.
label = S.values[length-tf.constant(2,dtype=tf.int32)]
label = tf.string_to_number(label,out_type=tf.int32)
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)

    for i in xrange(6):
        # Get an image tensor and print its value.
        key_val,label_val,image_tensor = sess.run([key,label,image])
        print(image_tensor.shape)
        print(key_val)
        print(label_val)


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

File Directory

./images/1/1.png
./images/1/2.png
./images/3/1.png
./images/3/2.png
./images/2/1.png
./images/2/2.png

Output:

 (881, 2079, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/1.png
 3
 (155, 2552, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/1.png
 2
 (562, 1978, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/2.png
 3
 (291, 2558, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/1.png
 1
 (157, 2554, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/2.png
 1
 (866, 936, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/2.png
 2
查看更多
登录 后发表回答