首页 > 解决方案 > 如何从 keras 中的图像批处理数据集中输出图像

问题描述

使用 keras 中的 image_dataset_from_directory 创建图像数据集后,如何以 numpy 格式从数据集中获取第一张图像,以便使用 pyplot.imshow 显示?

import tensorflow as tf
import matplotlib.pyplot as plt

test_data = tf.keras.preprocessing.image_dataset_from_directory(
    "C:\\Users\\Admin\\Downloads\\kagglecatsanddogs_3367a",
    validation_split=.1,
    subset='validation',
    seed=123)
for e in test_data.as_numpy_iterator():
    print(e[1:])

标签: pythontensorflowkeras

解决方案


在上面的代码中,e 不是图像,而是包含图像和标签的元组。
代码:

plt.figure(figsize=(10, 10))
class_names = test_data.class_names
for images, labels in test_data.take(1):
    for i in range(32):
        ax = plt.subplot(6, 6, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

您可以使用test_data.take(1)从 test_data 中获取单个批次并将其可视化。

您的输出将如下所示: 在此处输入图像描述


推荐阅读