问题描述
我正在尝试显示由Imagedatagenerator.flow()生成的图像,但我无法这样做。
我正在使用单个图像,并将其传递给.flow(img_path)生成增强图像,直到总数符合我们的要求为止:
total = 0
for image in imageGen:
total += 1
if total == 10:
break
.flow()
imageGen = aug.flow(image_path,batch_size=1,save_to_dir="/path/to/save_dir",save_prefix="",save_format='png')
解决方法
如果要使用图像路径,可以使用flow_from_directory,并传递包含单个图像的图像文件夹。要从生成器获取图像,请使用dir_It.next()
并访问第一个元素,因为此函数的返回是:
DirectoryIterator产生(x,y)元组,其中x是一个numpy数组,其中包含一批形状为(batch_size,* target_size,channels)的图像,而y是相应标签的numpy数组。
要显示图像,您可以使用plt.imshow
中的matplotlib
传递批次plt.imshow(img[0])
的第一张(也是唯一的)图像。
饲料结构
├── data
│ └── smile
│ └── smile_8.jpg
# smile_8.jpg shape (256,256,3)
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
datagen = keras.preprocessing.image.ImageDataGenerator(
rescale=1./255,rotation_range=180,width_shift_range=0.2,height_shift_range=0.2,)
dir_It = datagen.flow_from_directory(
"data/",batch_size=1,save_to_dir="output/",save_prefix="",save_format='png',)
for _ in range(5):
img,label = dir_It.next()
print(img.shape) # (1,3)
plt.imshow(img[0])
plt.show()