首页 > 解决方案 > 增强图像不存储在它们自己的类目录中

问题描述

我是 DCNN 的新手。此外,我正在研究图像数据增强,并且一直在编写增强代码。此外,我在数据集中有 5 个类,即草、花、水果、灰尘和树叶。因此,火车设置也由 8 个类组成。但是,在增强之后,所有增强数据都已存储在 train 文件夹中,但并未存储在它们各自的类中。除此之外,我已经手动应用了目录,例如:

directory = ('/content/dataset/train/Grass'),
save_to_dir = ('/content/dataset/train/Grass')

不幸的是,它不起作用,并且没有生成增强图像。

因此,我想使用已经存储在 train 文件夹中的原始数据来存储增强数据。简而言之,Grass 的增强数据,类将存储在 train 文件夹中的 Grass 类文件夹中,如下所示:

directory = ('/content/dataset/train/Grass'),
    save_to_dir = ('/content/dataset/train/Grass')

使用平台:Google Colab

我的代码:

from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
    rotation_range=45,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range = 0.2,
    zoom_range = 0.2, 
    horizontal_flip=True,
    fill_mode = 'nearest')

i = 0

for batch in datagen.flow_from_directory(directory = ('/content/dataset/train'),
                                         batch_size = 32,
                                         target_size = (256, 256),
                                         color_mode = ('rgb'),
                                         save_to_dir = ('/content/dataset/train'),
                                         save_prefix = ('aug'),
                                         save_format = ('png')):
  i += 1
  if i > 5:
    break

标签: pythontensorflowkerasdeep-learning

解决方案


你想要的是

import tensorflow as tf
import cv2
import os
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
sdir= r'c:\temp\people\dtest' # set this to the directory holding the images
ext='jpg' # specify the extension foor the aufmented images
prefix='aug' #set the prefix for the augmented images
batch_size=32 # set the batch size
passes=5  # set the number of time to cycle the generator
datagen = ImageDataGenerator( rotation_range=45, width_shift_range=0.2, height_shift_range=0.2, shear_range = 0.2,
                                zoom_range = 0.2,  horizontal_flip=True, fill_mode = 'nearest')
data=datagen.flow_from_directory(directory = sdir, batch_size = batch_size,  target_size = (256, 256),
                                 color_mode = 'rgb', shuffle=True)
for i in range (passes):
    images, labels=next(data)
    class_dict=data.class_indices
    new_dict={}
    # make a new dictionary with keys and values reversed
    for key, value in class_dict.items(): # dictionary is now {numeric class label: string of class_name}
        new_dict[value]=key    
    for j in range (len(labels)):                
        class_name = new_dict[np.argmax(labels[j])]         
        dir_path=os.path.join(sdir,class_name )         
        new_file=prefix + '-' +str(i*batch_size +j) + '.'  + ext       
        img_path=os.path.join(dir_path, new_file)        
        img=cv2.cvtColor(images[j], cv2.COLOR_BGR2RGB)
        cv2.imwrite(img_path, img)
print ('*** process complete')  

这将创建增强图像并将它们存储在其中包含原始图像的关联类子目录中。


推荐阅读