[FIXED] How to load image data for regression with keras?


I already have read now several tutorials that are giving instructions of how to import images for classification with Keras. As far as I see, all tutorials are just describing a multi-class scenario (e.g. cat/dog class.). These approaches don`t apply to my problem.

I want to do a regression that takes the images as input and returns images as output.
My question: How would I easily pass the image data to Keras, if there is no classification but regression?

With each pair of given input and output training data, I can’t find an easy import from:

├── input_data
│   ├── input0.png
|   ├── input1.png
|   └── ...
└── output_data
    ├── output0.png
    ├── output1.png
    └── ...

to this point:

x_train, x_valid, y_train, y_valid = train_test_split(inputs, outputs, test_size=0.2, shuffle= True)

What I have already tried:

  1. The Keras flow_from_directory method seems almost perfect and offers nice functionalities, but it only applies for classification data that is sorted in subdirectories.

  2. Secondly, there is this image import function, given by Tensorflow.

    from keras.preprocessing.image import img_to_array, load_img
    img = load_img('img.png') 
    x = img_to_array(img)

It is also straight forward as far as I know, there is only the possibility to open single images and not whole directories. This might be helpful if iterating over the whole directory, but since Keras has those nice preprocessing features, I am curious to know if there is a keras-like way. So my question:

Is there any comortable way to import large image datasets for regression?


As far as I know there is no specific function in Keras to load all images as a dataset. However, you can accomplish this by using a combination of os.walk() and Image.open(), something like the following would load all images into a list in one go:

import os
from PIL import Image  # or you can use the keras one to load images
def load_dataset(top_dir="input_data"):
    images_dataset = []
    for root, dirs, files in os.walk(top_dir):
        for name in files:
            # print(os.path.join(root, name))
            img = np.array(Image.open(os.path.join(root, name)))
    return images_dataset

Answered By – Yahya

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published