如何将文件名的数据集映射到文件内容的数据集

时间:2019-03-25 06:46:12

标签: tensorflow

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

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

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

dataset = dataset.map(parseline)

1 个答案:

答案 0 :(得分:1)

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

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())
相关问题