繁体   English   中英

Keras ImageDataGenerator 在保存到目录时无意中更改了我的图像的颜色

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

我正在尝试使用 ImageDataGenerator object 的流方法获取输入图像并保存该图像的 10 个增强版本。 问题是它无意中改变了我的图像颜色,即使我没有将 arguments 传递给 ImageDataGenerator class。

这是我的输入图像和代码,下面是我的 output 图像。 我正在使用 Tensorflow 2.2.0

输入图像

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 图像

图像的颜色完全不同。 任何帮助,将不胜感激。

问题是 ImageDataGenerator.flow 方法会自动重新缩放您的图像,而无法在使用 save_to_dir 参数时禁用它。 我能够使用以下代码解决此问题。

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

这是因为来自datagen的NumPy数组的dtype为float32,不支持dtype。 每当 dype 为float32时,它将在保存或显示之前剪切数组的值。
在保存之前尝试将来自 datagen 的 img_array 的 dtype 转换为int32uint8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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