TensorFlow图像读取队列为空

时间:2017-07-05 16:08:35

标签: machine-learning tensorflow computer-vision

我正在尝试使用管道将图像读取到CNN。我使用string_input_producer()来获取文件名的队列,但似乎没有做任何事情就挂在那里。以下是我的代码,请给我一些如何使其工作的建议。

def read_image_file(filename_queue, labels):
    reader = tf.WholeFileReader()
    key, value = reader.read(filename_queue)
    image = tf.image.decode_png(value, channels=3)
    image = tf.cast(image, tf.float32)
    resized_image = tf.image.resize_images(image, [224, 112])
    with tf.Session() as sess:
        label = getLabel(labels, key.eval())
    return resized_image, label

def input_pipeline(filename_queue, queue_names, batch_size, num_epochs, labels):
    image, label = read_image_file(filename_queue, labels)
    min_after_dequeue = 10 * batch_size
    capacity = 20 * batch_size
    image_batch, label_batch = tf.train.shuffle_batch(
        [image, label], batch_size=batch_size, num_threads=1, capacity=capacity,
        min_after_dequeue=min_after_dequeue)
    return image_batch, label_batch

train_queue = tf.train.string_input_producer(trainnames, shuffle=True, num_epochs=epochs)

train_batch, train_label = input_pipeline(train_queue, trainnames, batch_size, epochs, labels)

prediction = AlexNet(x)

#Training
with tf.name_scope("cost_function") as scope:
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label, logits=prediction(train_batch)))
    tf.summary.scalar("cost_function", cost)

    train_step = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(cost)

#Accuracy
with tf.name_scope("accuracy") as scope:
    correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.summary.scalar("accuracy", accuracy)

    merged = tf.summary.merge_all()

#Session
with tf.Session() as sess:
    print('started')
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord, start=True)
    sess.run(threads)

    try:
        for step in range(steps_per_epch * epochs):
            print('step: %d' %step)
            sess.run(train_step)
    except tf.errors.OutOfRangeError as ex:
        pass

    coord.request_stop()
    coord.join(threads)

1 个答案:

答案 0 :(得分:0)

由于未定义get_label方法,您的代码并非完全自包含。

但很可能你所遇到的问题来自read_image_file方法中的这些行:

with tf.Session() as sess:
    label = getLabel(labels, key.eval())

key.eval部分尝试将尚未启动的队列的元素出列。 在定义输入管道之前不应创建任何会话(也不要尝试评估key(可能还有labels))。 get_label方法只应对labelskey执行张量操作并返回label张量..

例如,您可以使用这些tensor string operations,这样它们就会成为图表的一部分。