在Tensorflow中使用标签加载图像

时间:2016-09-12 12:35:30

标签: image python-2.7 tensorflow labels

我想在tensorflow中加载带有目录标签的图像进行培训。

写完一些线后,我现在可以加载没有标签的图像。 有没有一种简单的方法可以将目录标签添加为标签?

/eye/eyeX.jpg→eye

/wall/wallX.jpg→墙

   import tensorflow as tf

   def read_my_file_format(filename_queue):
       reader = tf.WholeFileReader()
       key, value = reader.read(filename_queue)
       example = tf.image.decode_jpeg(value, channels=1)
       casted_example = tf.cast(example, tf.float32)
       resized_example = tf.image.resize_images(casted_example, 28, 28)
       return resized_example       

   def input_pipeline(filenames, batch_size):
       filename_queue = tf.train.string_input_producer(filenames)
       example = read_my_file_format(filename_queue)
       batch_size
       min_after_dequeue = 10000
       capacity = min_after_dequeue + 3 * batch_size
       example_batch, label_batch = tf.train.shuffle_batch(
           [example, 'DirectoryLabels?'], batch_size=batch_size, apacity=capacity,
           min_after_dequeue=min_after_dequeue)
       return example_batch, label_batch       

   root_dir = "/home/user/.."
   filenames1 = [(root_dir+"/eye/eye%d.jpg" % i) for i in range(10)]
   filenames2 = [(root_dir+"/wall/wall%d.jpg" % i) for i in range(10)]

   image_batch, label_batch = input_pipeline(filenames1,10)

   init_op = tf.initialize_all_variables()
   with tf.Session() as sess:
       sess.run(init_op)
       coord = tf.train.Coordinator()
       threads = tf.train.start_queue_runners(sess=sess, coord=coord)

       images = image_batch.eval()
       labels = label_batch.eval()
       print(images.shape)
       print(labels.shape)
       print(labels)

       coord.request_stop()
       coord.join(threads)

编辑:

如果您想知道如何开始使用tensorflow而不用unsing tensorflow来加载数据,那么只需创建自己的python脚本即可。 这是我所做的一小部分:

def load_image(filename):
    image = Image.open(filename)
    image = ImageOps.fit(image, (image_height, image_width))
    if image_channels == -1:
        image = image.convert('1')
    if image_channels == 1:
        image = ImageOps.grayscale(image)
    #image.show()
    return image    

def load_image_as_2d_array(filename):
    image = load_image(filename)
    i_arr = np.asarray(image)
    i_arr = [float(i) for i in i_arr]
    return i_arr    

def load_image_as_1d_array(filename):
    image = load_image(filename)
    i_arr = np.asarray(image)
    i_arr = i_arr.flatten()
    i_arr = [float(i) for i in i_arr]
    return i_arr

然后,您可以使用文件名作为标签,并编写类似于mnist示例的train.next_batch(batch_size)方法。

0 个答案:

没有答案