【问题标题】:Image augmentation with Tensorflow so All classes have EXACT SAME number of images使用 Tensorflow 进行图像增强,因此所有类都具有完全相同数量的图像
【发布时间】:2021-07-03 07:27:21
【问题描述】:

我想为动物分类做多类图像分类。问题是我的数据集对于每个类都有不同数量的图像,并且差异非常可怕。例如:

在此示例中,数据集包含 3 个类别的 320 张图像。 A类有125张图片,B类有170张图片,C类只有25张图片,我希望增加这些类因此每个类别将有 200 张图像,这意味着 600 张图像均匀分布到这 3 个类别。

但是,就我而言,我的数据集中有 60 个类。我怎样才能增加所有这些,以便它们对所有类都有完全相同数量的图像?

【问题讨论】:

    标签: python tensorflow keras image-classification image-augmentation


    【解决方案1】:

    这需要大量编码,但您可以使用 ImageDataGenerator 生成增强图像并将它们存储在指定目录中。生成器的文档是 here. 或者,您可以使用 cv2 或 PIL 等模块来提供转换图像的功能。以下是您可以与 cv2 一起使用的代码。注意查找 cv2 文档以了解如何指定代码注释中所述的图像转换。代码如下

    import os
    import cv2
    file_number =130 # set this to the number of files you want
    sdir=r'C:\Temp\dummydogs\train' # set this to the main directory that contains yor class directories
    slist=os.listdir(sdir)
    for klass in slist:
        class_path=os.path.join(sdir, klass)
        filelist=os.listdir(class_path)
        file_count=len(filelist)
        if file_count > file_number:
            # delete files from the klass directory because you have more than you need
            delta=file_count-file_number
            for i in range(delta):
                file=filelist[i]
                fpath=os.path.join (class_path,file)
                os.remove(fpath)
        else:
            # need to add files to this klass so do augmentation using cv3 image transforms
            label='-aug' # set this to a string that will be part of the augmented images file name 
            delta=file_number-file_count
            for i in range(delta):
                file=filelist[i]
                file_split=os.path.split(file)
                index=file_split[1].rfind('.')
                fname=file[:index]
                ext=file[index:]
                fnew_name=fname + '-' +str(i) +'-' + label + ext
                fpath=os.path.join(class_path,file)
                img=cv2.imread(fpath)
                img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
                # look up cv2 documentation and apply image transformation code here
                dest_path=os.path.join(class_path, fnew_name)
                cv2.imwrite(dest_path,img)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2015-04-24
      • 2015-07-20
      • 2016-04-20
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多