如何在 keras 中使用 ImageDataGenerator 和 flow_from_directory 保存增强图像

问题描述

我想在 Keras 中使用 ImageDataGenerator 增强两个不同目录(文件夹:良性/恶性)中的图像。

然后我想将每个类的增强图像保存在一个单独的文件夹中。

我的目录结构如下:

dataset
|   
|-- original_images
|   |                        
|   |-- benign                  
|   |    |-- benign_image1.png
|   |    |-- benign_image2.png
|   |    |-- ...
|   |
|   |-- malignant                   
|        |-- malignant_image1.png
|        |-- malignant_image2.png
|        |-- ...  
|   
|-- augmented_images
    |                        
    |-- augmented_benign                <-- Here i want to save augmented images of benign folder   
    |    |-- augmented_img1.png
    |    |-- augmented_img2.png
    |    |-- ...
    |
    |-- augmented_malignant             <-- Here i want to save augmented images of malignant folder
         |-- augmented_img1.png
         |-- augmented_img2.png
         |-- ...  

我的问题是我无法区分这两个类的增强图像,因为它们都将存储在同一个文件夹中。

实际上,我只能为“save_to_dir”参数设置一个文件夹路径,以便在那里存储图像。

正如我提到的,所有增强图像都将保存在一个文件夹 (augmented_images) 中。

你们能告诉我如何将每个类的增强图像保存在单独的文件夹(augmented_benignaugmented_malignant)中吗?

我写的代码是这样的:

from keras.preprocessing.image import ImageDataGenerator

img_dir_path = "D:/dataset/original_images"
save_dir_path = "D:/dataset/augmented_images"

datagen = ImageDataGenerator(rotation_range=90)

data_generator = datagen.flow_from_directory(
    img_dir_path,target_size=(128,128),color_mode="rgb",batch_size=20,save_to_dir="save_dir_path",class_mode="binary",save_prefix="augmented",save_format="png")

for i in range(10):
    data_generator.next()

解决方法

下面的代码应该给你你想要的。我测试了它,它完成了工作。 我注意到的一件事是当你设置 rotation_range=90 时,图像是 似乎在 -90 度到 + 90 度之间随机旋转。这有点意外。

sdir=r'c:\temp\dataset'
aug_dir=os.path.join(sdir,'augmented_images')
if os.path.isdir(aug_dir): # see if aug_dir exists if so remove it to get a clean slate
    shutil.rmtree(aug_dir)
os.mkdir(aug_dir) # make a new empty aug_dir
filepaths=[]
labels=[]
# iterate through original_images and create a dataframe of the form filepaths,labels
original_images_dir=os.path.join(sdir,'original_images')
for klass in ['benign','malignant']:
    os.mkdir(os.path.join(aug_dir,klass)) # make the class subdirectories in the aug_dir
    classpath=os.path.join(original_images_dir,klass) # get the path to the classes (benign and maligant)
    flist=os.listdir(classpath)# for each class the the list of files in the class    
    for f in flist:        
        fpath=os.path.join(classpath,f) # get the path to the file
        filepaths.append(fpath)
        labels.append(klass)
    Fseries=pd.Series(filepaths,name='filepaths')
    Lseries=pd.Series(labels,name='labels')
df=pd.concat([Fseries,Lseries],axis=1) # create the dataframe
gen=ImageDataGenerator( rotation_range=90)
groups=df.groupby('labels') # group by class
for label in df['labels'].unique():  # for every class               
    group=groups.get_group(label)  # a dataframe holding only rows with the specified label 
    sample_count=len(group)   # determine how many samples there are in this class  
    aug_img_count=0
    target_dir=os.path.join(aug_dir,label)  # define where to write the images    
    aug_gen=gen.flow_from_dataframe( group,x_col='filepaths',y_col=None,target_size=(128,128),class_mode=None,batch_size=1,shuffle=False,save_to_dir=target_dir,save_prefix='aug-',save_format='jpg')
    while aug_img_count<len(group):
        images=next(aug_gen)            
        aug_img_count += len(images) 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...