【问题标题】:ImageDataGenerator rescaling to [-1,1] instead of [0,1]ImageDataGenerator 重新缩放为 [-1,1] 而不是 [0,1]
【发布时间】:2020-10-31 08:05:37
【问题描述】:

我正在使用 Keras Tensorflow ImageDataGenerator,通常它与重新缩放因子 1./255 一起使用,以将初始值从 0 重新缩放到 255 到 0 到 1。但是,我想将其重新缩放到 -1,1 范围。

所以而不是:

train_image_generator = ImageDataGenerator(
    rescale=1./255,
)

我试过了:

train_image_generator = ImageDataGenerator(
    rescale=((1./127.5)-1)
)

接下来,这将应用于目录:

train_datagen = train_image_generator.flow_from_directory(
  directory=training_dir,
  target_size=(x, y),
  shuffle=True,
  batch_size=x,
  class_mode='binary'
)

检查一些值可以这样完成:

train_datagen[1]

但是根据documentation,这是我们用来将数据乘以提供的值的一个因素。所以它只能是一个用于乘法的因子,所以在这里减去 1 是没有意义的,因为数据是使用值 -0.99215686275 重新缩放的,而且当我检查实际值时,我确实可以看到负值,比如 -130。二十。所以这不起作用。由于我想稍后使用预训练的 MobileNet V2,因此我需要将其重新缩放为 -1,1 而不是 0,1,所以我的问题是,我该怎么做?

我不是在说about a way of avoiding using ImageDataGenerator

def format_example(image, label):
  image = tf.cast(image, tf.float32)
  image = (image/127.5) - 1
  image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))
  return image, label

等等。

所以我想使用 ImageDataGenerator。所以我可以重新缩放 1.0/127.5,但我仍然需要减去 1。有没有办法稍后从 train_datagen 中的值中减去 1?类似的东西

train_datagen.actualvalues-1

(我知道这不起作用。)

此外: 我需要一个与图像增强一起使用的解决方案,所以通常我有:

train_image_generator = ImageDataGenerator(
    horizontal_flip=True,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    fill_mode="nearest",
    zoom_range=0.2,
    rescale=((1./127.5)-1) #1./255,
)

现在,我唯一的问题是 rescale=((1./127.5)-1) 不起作用。我该如何解决这个问题,如何重新调整为 [-1,1] 而不是 [0,1]?

【问题讨论】:

    标签: python tensorflow image-processing keras


    【解决方案1】:

    使用 preprocessing_function 参数。

    def prep_fn(img):
        img = img.astype(np.float32) / 255.0
        img = (img - 0.5) * 2
        return img
    
    gen = ImageDataGenerator(
        preprocessing_function=prep_fn
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      相关资源
      最近更新 更多