【问题标题】:Using a dataset of filenames, create a dataset of images to tuples使用文件名数据集,将图像数据集创建为元组
【发布时间】:2020-08-29 21:28:22
【问题描述】:

我在一个文件夹中创建了一个包含许多图像文件名的 tensorflow 数据集。这些图像被命名为 [index].jpg,其中 index 是一些用于识别图像的整数。我有一个字符串“索引”字典,可以将其标记为元组。如何使用 tf.data.Dataset.map 将索引映射到标签元组?

这是我试图传递给 map 函数的 map_func:

def grabImages(filepath):
   index = getIndexFromFilePath(filepath)
   img = tf.io.read_file(filepath)
   img = translateImage(img)
   dictionary = getLabelDictionary()
   return index, img

dictionary 是标签 dict 的索引,index 是文件路径的索引,如 tf.Tensor,img 是文件路径中的预处理图像。

这会返回一个带有索引的数据集,作为张量,映射到相应的图像。有没有办法使用dictionary 使用dictionary[index] 之类的东西来获取index 的标签?基本上就是想找到index的字符串内容。

我曾尝试在grabImages 函数中将.numpy().eval() 与当前会话一起使用,但都不起作用。

【问题讨论】:

  • 您能否提供所需的示例输出场景?因为这很难理解。

标签: python tensorflow


【解决方案1】:

这是一个示例,说明如何在 tf.data.Dataset.map 函数中获取张量的字符串部分。

以下是我在代码中实现的步骤。

  1. 你必须用tf.py_function(get_path, [x], [tf.string])装饰地图功能。您可以找到有关 tf.py_function here 的更多信息。
  2. 您可以通过在 map 函数中使用 bytes.decode(file_path.numpy()) 来获取您的字符串部分。

代码 -

%tensorflow_version 2.x
import tensorflow as tf
import numpy as np

def get_path(file_path):
    print("file_path: ",bytes.decode(file_path.numpy()),type(bytes.decode(file_path.numpy())))
    return file_path

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(get_path, [x], [tf.string]))

for one_element in train_dataset:
    print(one_element)

输出 -

file_path:  /content/bird.jpg <class 'str'>
(<tf.Tensor: shape=(), dtype=string, numpy=b'/content/bird.jpg'>,)

希望这能回答你的问题。

【讨论】:

  • @Andrew Wiedenmann - 如果它回答了您的问题,请投票并接受答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-12-02
  • 2017-01-10
  • 1970-01-01
  • 2018-10-31
  • 2020-09-10
  • 2018-11-23
  • 2020-08-08
  • 1970-01-01
相关资源
最近更新 更多