在tensorflow中加载图像文件夹

在tensorflow中加载图像文件夹,tensorflow,neural-network,directory,loadimage,Tensorflow,Neural Network,Directory,Loadimage,我是tensorflow的新手,但我已经遵循并执行了他们推广的教程以及网络上的许多其他教程。 我在MNIST图像上做了一个小小的卷积神经网络。没有什么特别的,但我想测试我自己的图像。 现在我的问题来了:我创建了几个文件夹;每个文件夹的名称是其中的图像所属的类(标签) 图像具有不同的形状;我的意思是它们没有固定的尺寸 如何加载它们以用于Tensorflow 我在StackOverflow和其他Q/A网站上学习了很多教程和答案。但是,我仍然不知道如何做到这一点。用于从目录加载图像和标签的示例输入管道

我是tensorflow的新手,但我已经遵循并执行了他们推广的教程以及网络上的许多其他教程。 我在MNIST图像上做了一个小小的卷积神经网络。没有什么特别的,但我想测试我自己的图像。 现在我的问题来了:我创建了几个文件夹;每个文件夹的名称是其中的图像所属的类(标签)

图像具有不同的形状;我的意思是它们没有固定的尺寸

如何加载它们以用于Tensorflow


我在StackOverflow和其他Q/A网站上学习了很多教程和答案。但是,我仍然不知道如何做到这一点。

用于从目录加载图像和标签的示例输入管道脚本。在此之后,您可以进行预处理(调整图像大小等)

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)
文件目录

./images/1/1.png
./images/1/2.png
./images/3/1.png
./images/3/2.png
./images/2/1.png
./images/2/2.png
输出:

 (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

tf.data
API(tensorflow 1.4及以后版本)非常适合这样做。管道的外观如下所示:

  • 创建一个迭代所有示例的初始
    tf.data.Dataset
    对象
  • (如果训练)
    洗牌
    /
    重复
    数据集
  • 映射
    通过某种功能使所有图像大小相同
  • 批处理
  • (可选)
    预回迁
    ,告知您的程序在网络处理当前批次时收集预处理后续批次的数据;及
  • 并获取输入
创建初始数据集有多种方法(请参阅以获得更深入的答案)

具有Tensorflow数据集的TFR记录 支持tensorflow 1.12版以后的版本,为创建tfrecord数据集提供了一个相对简单的API,还可以自动处理数据下载、分片、统计数据生成和其他功能

见例。里面有很多图书保管的东西(下载URL、引用等),但技术部分归结为指定
功能
和编写
\u生成示例
函数

features=tfds.features.FeaturesDict({
“image”:tfds.features.image(形状=(\u TILES\u SIZE,)*2+(3,),
“标签”:tfds.features.ClassLabel(
名称=_类名称),
“文件名”:tfds.features.Text(),
})
...
定义生成示例(自、根目录):
root\u dir=os.path.join(root\u dir、\u TILES\u SUBDIR)
对于i,枚举中的类名称(\u类名称):
class\u dir=os.path.join(root\u dir,\u class\u subdir(i,class\u name))
fns=tf.io.gfile.listdir(类目录)
对于已排序的fn(fns):
image=_load_tif(os.path.join(class_dir,fn))
屈服{
“形象”:形象,
“标签”:类别名称,
“文件名”:fn,
}

您还可以使用较低级别的操作生成
tfrecords

通过
tf.data.Dataset.map和
tf.py_函数加载图像
或者,您可以从
tf.data.Dataset.map
中的文件名加载图像文件,如下所示

image_paths, labels = load_base_data(...)
epoch_size = len(image_paths)
image_paths = tf.convert_to_tensor(image_paths, dtype=tf.string)
labels = tf.convert_to_tensor(labels)

dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))

if mode == 'train':
    dataset = dataset.repeat().shuffle(epoch_size)


def map_fn(path, label):
    # path/label represent values for a single example
    image = tf.image.decode_jpeg(tf.read_file(path))

    # some mapping to constant size - be careful with distorting aspec ratios
    image = tf.image.resize_images(out_shape)
    # color normalization - just an example
    image = tf.to_float(image) * (2. / 255) - 1
    return image, label


# num_parallel_calls > 1 induces intra-batch shuffling
dataset = dataset.map(map_fn, num_parallel_calls=8)
dataset = dataset.batch(batch_size)
# try one of the following
dataset = dataset.prefetch(1)
# dataset = dataset.apply(
#            tf.contrib.data.prefetch_to_device('/gpu:0'))

images, labels = dataset.make_one_shot_iterator().get_next()
我从未在分布式环境中工作过,但我从未注意到在
tfrecords
上使用这种方法会对性能造成影响。如果您需要更多自定义加载功能,也可以查看


更多一般信息和性能说明

要加载相同大小的图像,请使用以下命令:

tf.keras.preprocessing.image_dataset_from_directory(dir)

文档:

首先,感谢您的快速回复。我尝试了您的代码片段,它引发了以下错误。tensorflow.python.framework.errors\u impl.OutOfRangeError:FIFOQueue'\u 0\u input\u producer'已关闭,元素不足(请求的1,当前大小为0)[[Node:ReaderReadV2=ReaderReadV2[\u device=“/job:localhost/replica:0/task:0/cpu:0”](WholeFileReaderV2,input\u producer)]我认为无法找到图像。文件夹的路径是否正确?用几张图片试试。我用以下两行代码修复了元素不足错误:
sess.run(tf.local\u variables\u initializer())
sess.run(tf.global\u variables\u initializer())
你把这些行放在哪里了?我也有同样的错误:/@pnz:就在运行文件名匹配所需的
之前。
行,左边有4个空格。对于那些获得
名称的人错误:名称“load\u base\u data”没有定义。
:我想
load\u base\u data(…)
可以被类似
[“mydata/cats”、“mydata/dogs”],[0,1]的内容替换
。对于那些获得
名称错误:未定义全局名称“out\u shape”和其他错误,我想在文件开头添加以下行后,它可能会工作得更好:
将tensorflow导入为tf
模式='train'
out\u shape=tf。将\u转换为\u张量([100100])
批量大小=10
。不过,我不确定这些值是否有意义。