简体   繁体   中英

Keras ImageDataGenerator unintentionally changes the color of my images when saving to directory

I'm trying to take an input image and save 10 augmented versions of that image using the flow method of a ImageDataGenerator object. The issue is that it's unintentionally changing the color of my image, even when I pass no arguments into the ImageDataGenerator class.

Here's my input image and code with my output image below. I'm using Tensorflow 2.2.0

input image

from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator

img = image.load_img(r'C:\Users\me\Desktop\test.jpg')
img_array = image.img_to_array(img)
img_array = img_array.reshape((1,) + img_array.shape)

datagen = ImageDataGenerator() #no arguments, no augmentations
save_to_dir = r'C:\Users\me\Desktop'

i = 0
for batch in datagen.flow(img_array, batch_size=1, save_to_dir=save_to_dir, save_format='jpg'):
    if i == 9:
        break
    i += 1

output image

The color of the image is drastically different. Any help would be appreciated.

The issue is that the ImageDataGenerator.flow method automatically re-scales your image without being able to disable it while using the save_to_dir argument. I was able to fix this issue with the following code.

from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator

img = image.load_img(r'C:\Users\me\Desktop\test.jpg')
img_array = image.img_to_array(img)
img_array = img_array.reshape((1,) + img_array.shape)

datagen = ImageDataGenerator() #no arguments, no augmentations
save_to_dir = r'C:\Users\me\Desktop'

i = 0
for batch in datagen.flow(img_array, batch_size=1, save_format='jpg'):
    img_save = image.array_to_img(batch[0], scale=False) #scale=False did the trick
    img_save.save(save_to_dir + fr'\augment_{i}.jpg') #save image manually
    if i == 9:
        break
    i += 1

Its because the NumPy array that comes from datagen has dtype as float32 which is not supported dtype. Whenever the dype is float32 it will clip the value of array before saving or displaying.
Try converting the dtype of img_array that comes from datagen to int32 or uint8 before saving.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM