python - 在 Python 中使用 Keras 进行图像增强
问题描述
如何为存储在文件夹中的多个图像应用 Keras 图像增强?
PS:我为单个图像尝试了以下代码,并且效果很好。
有人可以帮我解决多张图片吗?
enter code here
from keras.preprocessing import image
import matplotlib.pyplot as plt
import cv2
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
rotation_range = 30,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = 0.2,
fill_mode = "nearest")
for img in glob.glob("Images/*/*.jpg"):
cv_img = cv2.imread(img)
cv_resize = cv2.resize(cv_img,(200,200))
cv_norm_img = cv_resize/255.0
break
cv_norm_img = np.array(cv_norm_img)
input_batch = cv_norm_img.reshape((1,*cv_norm_img.shape))
i = 0
for output_batch in datagen.flow(input_batch,batch_size=1):
plt.figure()
imgplot = plt.imshow(image.img_to_array(output_batch[0]))
i+=1
if i==10:
break
plt.axis('off')
plt.show
解决方案
最简单的方法是使用目录中的 ImageDataGenerator.flow。文档位于https://keras.io/preprocessing/image/。images 将是一个形状数组 (batch_size, 200, 200, 3) 注意:每次运行它时,它都会在 save_to_dir 中放入更多的图像,因此您可能不想包含该参数。您可以通过 img1=images[0]、img2=images[1] 等方式访问单个图像 如下设置您的生成器
datagen = ImageDataGenerator(rotation_range = 30, width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
rescale=1/255,
horizontal_flip = True,
fill_mode = "nearest")
data=datagen.flow_from_directory(your_dir, target_size=(200, 200),
batch_size=your_file_count, shuffle=False,
save_to_dir=your_save_dir,save_format='png',
interpolation='nearest')
images,labels=data.next()
推荐阅读
- qlikview - 在 qlik 意义上更改分布图的颜色
- javascript - mapbox-gl 未聚集的点重叠为一个圆圈
- c# - 如何在 c# linq 中的对象内为对象创建 where 条件?
- javascript - 在应用程序启动时运行计算代码 html 表
- c++ - quit() 函数中的 C++ 可能的范围问题
- office365 - Office 365 导入作业 PST Rest API
- python - 使用 numpy 在 python 中编写 L-BFGS 最小化函数时出错
- sql - 具有可能具有“多种类型的 NULL”值的列的 SQL 表
- javascript - 基于 Bootstrap 的 Modal 没有出现在 React / Next JS 应用程序中
- python - 使用 plotly 在 3d 散点图中绘制 3d 框