Python 使用文件名数据集,将图像数据集创建为元组

Python 使用文件名数据集,将图像数据集创建为元组,python,tensorflow,Python,Tensorflow,我创建了一个tensorflow数据集,其中包含文件夹中许多图像的文件名。这些图像被命名为[index].jpg,其中index是用于标识图像的某个整数。我有一个字符串“索引”字典,将标签作为元组。如何使用tf.data.Dataset.map将索引映射到标签元组 下面是我试图传递给map函数的map_func: def图像(文件路径): index=getIndexFromFilePath(文件路径) img=tf.io.read\u文件(文件路径) img=平移图像(img) diction

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

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

def图像(文件路径):
index=getIndexFromFilePath(文件路径)
img=tf.io.read\u文件(文件路径)
img=平移图像(img)
dictionary=getLabelDictionary()
返回索引
其中dictionary是标签dict的索引,index是文件路径的索引,如tf.Tensor,img是文件路径处的预处理图像

这将返回一个数据集,其索引作为张量映射到相应的图像。有没有一种方法可以使用
dictionary
或类似
dictionary[index]
的方法来获取
索引的标签?基本上,我想找到索引的字符串内容


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

下面是一个如何在
tf.data.Dataset.map
函数中获取张量的字符串部分的示例

下面是我在代码中实现的实现这一点的步骤

  • 您必须使用
    tf.py\u函数(get\u path,[x],[tf.string])
    来装饰map函数。您可以找到更多关于tf.py_函数的信息
  • 您可以使用map函数中的
    bytes.decode(file\u 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'>,)
    
    文件路径:/content/bird.jpg
    (,)
    

    希望这能回答您的问题。

    您能提供所需的示例输出场景吗?因为这很难理解。@Andrew Wiedenmann-如果答案回答了你的问题,请投票并接受答案。非常感谢。