首页 > 解决方案 > 如何将文件名数据集映射到文件内容数据集

问题描述

例如,我有一个 tensorflow 数据集,其中每个元素都是 atf.string Tensor代表图像文件的文件名。现在我想将此文件名数据集映射到图像内容张量数据集。

我写了这样的代码,但它不起作用,因为 map 函数不能急切地执行。(引发错误说张量类型没有名为 numpy 的属性。)

def parseline(line):
    filename = line.numpy()
    image = some_library.open_image(filename).to_numpy()
    return image

dataset = dataset.map(parseline)

标签: tensorflow

解决方案


基本上,可以通过以下方式完成:

path = 'path_to_images'

files = [os.path.join(path, i) for i in os.listdir(path)] # If you need to create a list of filenames, because tf functions require tensors

def parse_image(filename):
    file = tf.io.read_file(filename) # this will work only with filename as tensor
    image = tf.image.decode_image(f)
    return img

dataset = tf.data.Dataset.from_tensor_slices(files)
dataset = dataset.map(parse_image).batch(1)

如果您处于渴望模式,只需遍历数据集

 for i in dataset:           
    print(i)

如果没有,您将需要一个迭代器

iterator = dataset.make_one_shot_iterator()
with tf.Session as sess:
    sess.run(iterator.get_next())

推荐阅读