Python 使用TensorFlow读取图像并从路径中提取标签

Python 使用TensorFlow读取图像并从路径中提取标签,python,tensorflow,image-recognition,Python,Tensorflow,Image Recognition,我正在尝试使用tensorflow读取图像文件,并从以下路径获取标签: import tensorflow as tf filename_queue = tf.train.string_input_producer( tf.matching_files( tf.constant(["./positive_images/*.jpg",

我正在尝试使用tensorflow读取图像文件,并从以下路径获取标签:

import tensorflow as tf

filename_queue = tf.train.string_input_producer(
                                 tf.matching_files(
                                    tf.constant(["./positive_images/*.jpg",
                                                "./negative_images/*.jpg"])))

image_reader = tf.WholeFileReader()

file_name, image_file = image_reader.read(filename_queue)
label = tf.map_fn(lambda x: "positive" in x, file_name)
image = tf.image.decode_jpeg(image_file, channels=1)

with tf.Session() as sess:
    # Required to get the filename matching to run.
    tf.global_variables_initializer()

    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    filename1 = sess.run([label])
    print(filename1)

    image_tensor = sess.run([image])
    print(image_tensor)

    coord.request_stop()
    coord.join(threads)
但是我得到了一个错误:

in map_fn raise ValueError("elems must be a 1+ dimensional Tensor, not a scalar")
ValueError: elems must be a 1+ dimensional Tensor, not a scalar

读取图像似乎可行,但无法正确解析文件名。我做错了什么?

您收到的错误消息清楚地告诉您问题出在哪里:tf.map_fn()的第二个参数应该是1-D(或更多)张量,您正在传递WholeFileReader.read()的返回,这是一个“字符串标量张量”(零-D)。我不是tensorflow方面的专家,但看起来read()函数每次调用都会返回一个(名称、内容)对,而不是像您预期的那样生成两个序列。
read()
确实会返回两个标量张量。我强烈建议使用
tf.data
API。它们更干净,而且通常更快。您可以在这里找到一个读取图像的示例:我用以下命令解决了它:
X\u train\u images\u decoded=tf.map\u fn(lambda X:tf.image.decode\u image(tf.read\u file(X),channels=1),X\u path,dtype=tf.uint8
X\u path是一个一维张量,其中包含我使用函数os.walk创建的图像路径