【问题标题】:Display an image and its label from DataFrameIterator从 DataFrameIterator 显示图像及其标签
【发布时间】:2021-07-12 18:24:06
【问题描述】:

我正在从数据集(使用 flow_from_dataframe 创建)中迭代图像,并希望使用 pyplot 及其相应的标签显示图像

training_dataset = train_dataset_gen.flow_from_dataframe(dataframe=train_df,
                                                     directory="./Data/train/",
                                                     x_col="file",
                                                     y_col="label",
                                                     shuffle=True,
                                                     batch_size=BATCH_SIZE,
                                                     target_size=IMG_SIZE,
                                                     class_mode="sparse",
                                                     subset="training")

我可以显示图像,但标签是 0 和 1 的数组。

for _ in range(len(training_dataset.filenames)):
     image, label = training_dataset.next()
     # display the image from the iterator
     plt.imshow(image[0])
     plt.title(training_dataset.)
     plt.show()

如何获得真正的标签值?

这是通过反转字典来解决的:

class_names=training_dataset.class_indices

new_dict={}
for key, value in class_names.items():
    new_dict[value]=key

【问题讨论】:

    标签: tensorflow machine-learning computer-vision


    【解决方案1】:

    ImageDataGenerator 有一个属性 .class_indices。它是一个形式的字典

    {'class name': class index}
    

    其中类名是一个字符串,它是数据框标签列中的标签名称。类索引是与类名关联的整数。这是您在打印标签时将看到的值(因为您使用了 class_mode='sparse')。 例如,在您的数据框中,如果您的标签是猫、狗,那么您的 class_indices 将是

    {'cat':0, 'dog':1}
    

    如下图倒转这个字典很方便

    for key, value in class_dict.items():
        new_dict[value]=key 
    

    现在 new_dict 的格式为 {0:'cat', 1:'dog'}。所以现在修改你的代码如下

    for _ in range(len(training_dataset.filenames)):
         image, label = training_dataset.next()
         # display the image from the iterator
         plt.imshow(image[0])
         label_name=new_dict[label[0]] # note you are only showing the first image of the batch
         plt.title(label_name)
         plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2021-11-30
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多