Why gen.flow_from_directory() accept only a folder with 2 folder each of them present a class?

Viewed 344

Clustering task :

I have a folder with name "train" which contain my own train image dataset (1000) and all images are unlabeled ( Don't have two folder for class1 and class2) I would like to import my dataset with tf.data.Dataset.from_generator like below

train_gen = tf.keras.preporocessing.image.ImageDataGenerator()
train_set = train_gen.flow_from_directory('/path/train')

I find this message when I run my code: Found 0 images belonging to 0 classes

3 Answers

Create a directory inside your train directory.
Add all the images inside that directory.

And use the above code with class_mode = None
Code:

train_gen = tf.keras.preprocessing.image.ImageDataGenerator()
train_set = train_gen.flow_from_directory('path/train',class_mode = None)

Using class_mode = None, the generators will return only augmented images.

See here for complete options.

The ImageDataGenerator expects that the directory you specify will contain sub directories. Each sub directory is expected to contain images associated with a specific class. For example if you are trying to classify dog and cat images you would have a sub directory you could name dogs that contain images of dogs and a sub directory named cats that contain images of cats. In your case in the directory '/path/train' create a sub directory (name is arbitrary) and place your images in that sub directory. The generator will import these images in batches. You should get the message Found 1000 images belonging to 1 classes when the generator runs. Set the parameter class_mode=None in flow_from_directory. That will cause the generator to produce only images and no labels.

You can use this simple function:

def load(file_path):
    img = tf.io.read_file(file_path)
    img = tf.image.decode_png(img, channels=3)
    img = tf.image.convert_image_dtype(img, tf.float32)
    img = tf.image.resize(img, size=(100, 100)) # optional
    return img 

ds = tf.data.Dataset.from_tensor_slices(x).map(load)

next(iter(ds))
<tf.Tensor: shape=(100, 100, 3), dtype=float32, numpy=
 array([[[0.40976474, 0.47250983, 0.56270593],
         [0.4039216 , 0.4666667 , 0.5568628 ],
         [0.41176474, 0.48235297, 0.57254905],
         ...,
         [0.5620584 , 0.5812747 , 0.6775489 ],
         [0.53252923, 0.5579019 , 0.6559411 ],
         [0.5176471 , 0.5568628 , 0.6509804 ]]], dtype=float32)>
Related