首页 > 解决方案 > 如何处理改变图像分类中标签的增强?

问题描述

我正在尝试使用 Tensorflow 构建一个简单的网络,将人脸分类为 3 个类。

我想将图像增强应用到我的数据集,特别是horizontal_flip但我不能使用它,因为如果将此转换应用于看起来leftright的脸,我需要更改标签。

应用这种“标签更改”转换的最佳方法是什么?

标签: tensorflow

解决方案


棘手的问题但可行。最好的方法是使用数据框。我假设你有一个名为 faces 的目录。它有 3 个子目录 left(用于查看左侧图像)、right(用于查看右侧图像)和 center(用于查看正前方图像)首先要做的是创建一个数据框来保存图像的路径及其相关标签。

import pandas as pd
import cv2
sdir=r'c:\temp\faces'
sdir=r'C:\Temp\left right'
classlist=os.listdir(sdir) 
filepaths=[]
labels=[]    
for klass in classlist:
    classpath=os.path.join(sdir,klass)        
    flist=os.listdir(classpath)    
    for f in flist:
        fpath=os.path.join(classpath,f)        
        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)     
print('df length: ', len(df))

现在我们有了一个数据框。接下来创建一组目录来保存我们的增强图像

working_dir=sdir
aug_dir=os.path.join(working_dir, 'aug')
if os.path.isdir(aug_dir):
    shutil.rmtree(aug_dir)
os.mkdir(aug_dir)
for label in df['labels'].unique():
    dir_path=os.path.join(aug_dir,label)    
    os.mkdir(dir_path)

现在我们在 faces 目录中有一个子目录 aug。aug 目录有左、右、中 3 个子目录,用于存储增强图像。接下来创建水平翻转的图像并将它们存储在aug目录的正确子目录中

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     
    for i in range(len(group)):
        fpath=group['filepaths'].iloc[i]
        img=cv2.imread(fpath) # read in the file
        img=cv2.flip(img, 1)  # horizontally flip it
        fname=os.path.split(fpath)[1] # get the name of the file 
        if label=='center': # if processing center label images store in aug/center
            destpath=os.path.join(aug_dir, 'center', fname)           
        elif label== 'left': if processing left label images store in aug/right
            destpath=os.path.join(aug_dir, 'right', fname)            
        else: # if processing right labeled images store the result in aug/left
            destpath=os.path.join(aug_dir, 'left', fname )
            
        cv2.imwrite(destpath, img ) # write the flipped image to the destination

现在我们存储了增强图像,我们需要将其与原始图像结合起来

aug_fpaths=[]
aug_labels=[]
classlist=os.listdir(aug_dir)
for klass in classlist:
    classpath=os.path.join(aug_dir, klass)     
    flist=os.listdir(classpath)
    print (len(flist))
    for f in flist:        
        fpath=os.path.join(classpath,f)         
        aug_fpaths.append(fpath)
        aug_labels.append(klass)
Fseries=pd.Series(aug_fpaths, name='filepaths')
Lseries=pd.Series(aug_labels, name='labels')
aug_df=pd.concat([Fseries, Lseries], axis=1)
ndf=pd.concat([df,aug_df], axis=0).reset_index(drop=True)

数据框 ndf 现在包含原始图像和增强图像。从那里您可以将 ndf 拆分为 train_df、test_df 和 validation_df。然后使用 ImageDataGenerator.flow_from_dataframe 创建训练、测试和验证生成器


推荐阅读