gpt4 book ai didi

tensorflow - 在tensorflow中加载图像文件夹

转载 作者:行者123 更新时间:2023-12-04 01:22:28 33 4
gpt4 key购买 nike

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

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

如何加载它们以用于Tensorflow?

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

最佳答案

tf.data API(tensorflow 1.4及更高版本)非常适合此类情况。该管道将​​如下所示:


创建一个迭代所有示例的初始tf.data.Dataset对象
(如果经过培训)shuffle / repeat数据集;
map通过某些功能使所有图像具有相同大小;
batch;
(可选)prefetch告诉您的程序在网络处理当前批次时收集预处理的后续批次数据;和
并获取输入。


有多种创建初始数据集的方法(有关更深入的答案,请参见here

带有Tensorflow数据集的TFRecords

Tensorflow datasets支持tensorflow版本1.12及更高版本,提供了一个用于创建tfrecord数据集的相对简单的API,并且还自动处理数据下载,分片,统计信息生成和其他功能。

参见例如this image classification dataset implementation。那里有很多bookeeper内容(下载url,引文等),但是技术部分归结为指定features并编写_generate_examples函数

features = tfds.features.FeaturesDict({
"image": tfds.features.Image(shape=(_TILES_SIZE,) * 2 + (3,)),
"label": tfds.features.ClassLabel(
names=_CLASS_NAMES),
"filename": tfds.features.Text(),
})

...

def _generate_examples(self, root_dir):
root_dir = os.path.join(root_dir, _TILES_SUBDIR)
for i, class_name in enumerate(_CLASS_NAMES):
class_dir = os.path.join(root_dir, _class_subdir(i, class_name))
fns = tf.io.gfile.listdir(class_dir)

for fn in sorted(fns):
image = _load_tif(os.path.join(class_dir, fn))
yield {
"image": image,
"label": class_name,
"filename": fn,
}




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

通过 tf.data.Dataset.maptf.py_func(tion)加载图像

或者,您可以从 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.py_func

更多常规信息 here,以及性能说明 here

关于tensorflow - 在tensorflow中加载图像文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416764/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com