JoshW
JoshW

Reputation: 105

Keras ImageDataGenerator/flow_from_dir distorting image

Keras's InputDataGenerator seems to be messing with the training data.

Here is the original image (128x128 w/ 3 colors):

Dog

And this is what I'm getting from the InputDataGenerator (128x128 w/ 3 colors):

enter image description here

Downloading the image directly wouldn't work with windows (said image was corrupt).

Anybody know what's going on and how to fix it? It seems almost if every color is getting its own column or something weird like that.

from keras.preprocessing.image import ImageDataGenerator
import numpy as np
from PIL import Image

# Where ImageDataGenerator is getting data from
Data_Directory = 'C:/Users/user/PycharmProjects/ImageGAN/training/'

# Actual image location; Img is (128, 128, 3).
Image_location = r'C:/Users/user/PycharmProjects/ImageGAN/training/class1/dog.png'

datagen = ImageDataGenerator()
train_ds = datagen.flow_from_directory(Data_Directory, target_size=(128, 128))

data = train_ds.next()
imgdata = np.array(data[0])

print(imgdata.shape)        # (1, 128, 128, 3)
print(imgdata[0][0][55])    # [115. 80. 38.]

# Distorted image
img = Image.fromarray(imgdata[0], "RGB")
img.save(f"DogBroken.png")
img.show()

# Correct image
image = Image.open(Image_location).convert("RGB")
image.show()

Upvotes: 1

Views: 101

Answers (1)

ClaudiaR
ClaudiaR

Reputation: 3414

In order to keep the same dimension you should change the target_size arguments of the method flow_from_directory. In your case:

train_ds = datagen.flow_from_directory(Data_Directory, target_size=(128, 128))

To fix the issue apply .astype('uint8') to the numpy array:

img = Image.fromarray(imgdata[0].astype('uint8'), "RGB")

.astype('uint8') is used to convert the values to unsigned integers.

Upvotes: 1

Related Questions