如何绘制使用 ImageDataGenerator 加载的随机图像?

rdn*_*rdn 1 conv-neural-network keras tensorflow

我想绘制加载到 ImageDataGenrator 中的随机图像样本,我该怎么做?

我已经导入了模块,但我不知道如何获取图像

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255)
train = train_datagen.flow_from_directory(PATH, target_size = (IMG_SIZE, IMG_SIZE), batch_size = K, class_mode = None)

plt.imshow(?)

Run Code Online (Sandbox Code Playgroud)

Ger*_*y P 7

生成器将生成一个元组(图像、标签),其中图像具有形状(batch_size、image_size[0]、image_size[1]、num_channels)。参见下面的代码:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from IPython.core.display import display, HTML

image_size=224
batch_size=10
source_dir=r'c:\temp\birds\test'
save_dir=r'c:\temp\birds\storage'
rand_seed=123
# if you want to save the images set save_dir to a directory and save_formay to the format you want otherwise leave these values as None
test_gen=ImageDataGenerator(rescale = 1./255).flow_from_directory(source_dir,
                target_size=(image_size, image_size), batch_size=batch_size, color_mode='rgb',
                seed=rand_seed, shuffle=False, save_to_dir=save_dir,save_format="png" )
batch=next(test_gen)  # returns the next batch of images and labels 
print(batch[0].shape) # batch[0] is the images, batch[1] are the labels
img=batch[0][0]   # this is the first image  batch[0][1] would be the next image
print (img.shape)
plt.imshow(img)   # shows the first image

You can set shuffle=True to get the images in random order
Run Code Online (Sandbox Code Playgroud)