如何使用自定义数据生成器进行keras图像增强? [英] How to do keras image augmentation using custom data generator?

查看:94
本文介绍了如何使用自定义数据生成器进行keras图像增强?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Keras自定义生成器,我想对自定义数据生成器返回的数据应用图像增强技术.

I am using Keras custom generator and i want to apply image augmentation techniques on data returned from custom data generator.

我想要这些图像增强技术

I want these image augmentation techniques

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

这是keras定制生成器

This is keras custom generator

def __data_generation(self, list_IDs_temp):
  'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
  # Initialization
  X = np.empty((self.batch_size, *self.dim, self.n_channels))
  y = np.empty((self.batch_size), dtype=int)

      # Generate data
      for i, ID in enumerate(list_IDs_temp):
          # Store sample
          X[i,] = tfk.preprocessing.image.load_img(self.list_IDs[ID])
    
          # Store class
          y[i] = self.labels[ID]
    
      return X, tkf.utils.to_categorical(y, num_classes=self.n_classes)

推荐答案

还没有尝试过,但我想您可以在您的 ImageDataGenerator 实例中使用 flow 方法.例如,您的自定义类可能如下所示:

Haven't tried it but I guess you can use the flow method from your instance of ImageDataGenerator. For example, your custom class could look like this:

class CustomDataGenerator(tf.keras.utils.Sequence):
    
    def __init__(self, batch_size=32):
        self.batch_size = batch_size
        self.augmentor = ImageDataGenerator(
            rotation_range=40,
            width_shift_range=0.2,
            height_shift_range=0.2,
            shear_range=0.2,
            zoom_range=0.2,
            horizontal_flip=True,
            fill_mode='nearest'
        )

    ...

    def __data_generation(self, list_IDs_temp):
      'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
      # Initialization
      X = np.empty((self.batch_size, *self.dim, self.n_channels))
      y = np.empty((self.batch_size), dtype=int)

      # Generate data
      for i, ID in enumerate(list_IDs_temp):
          # Store sample
          X[i,] = tfk.preprocessing.image.load_img(self.list_IDs[ID])
    
          # Store class
          y[i] = self.labels[ID]

      X_gen = self.augmentor.flow(X, batch_size=self.batch_size, shuffle=False)
      """do not perform shuffle here, the shuffling is performed beforehand
       by your custom class anyway, you just want the transformations to be 
      applied, and above all you want to keep your images synced with the 
      labels.""" 
      
      return next(X_gen), tkf.utils.to_categorical(y, num_classes=self.n_classes)

这篇关于如何使用自定义数据生成器进行keras图像增强?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆