Search code examples
tensorflowartificial-intelligencereshapetensorflow2.0

Reshape image to [-1, 1] with ImageDataGenerator


Is it possible to reshape images in [0, 255] to [-1, 1] using ImageDataGenerator?

I have seen that I can multiply the image with a value using the reshape parameter, but that only gives me the possibility to reshape it to [0, 1]


Solution

  • You could use the preprocessing_function in Keras ImageDataGenerator class.

    preprocessing_function: function that will be applied on each input. The function will run after the image is resized and augmented. The function should take one argument: one image (Numpy tensor with rank 3), and should output a Numpy tensor with the same shape.

    #preprocessing_function function
    def changeRange(image):
    
       image[:, :, 0] = [(i/128.0)-1 for i in image[:, :, 0]]
       image[:, :, 1] = [(i/128.0)-1 for i in image[:, :, 1]]
       image[:, :, 2] = [(i/128.0)-1 for i in image[:, :, 2]]
    
       return image
    
    #data augementation
    train_datagen = ImageDataGenerator(
       rescale = None,
       preprocessing_function=changeRange)
    

    `