Home > Net >  How do I read two folders in a directory and combine them under one label using flow_from_directory?
How do I read two folders in a directory and combine them under one label using flow_from_directory?

Time:04-12

Tensorflow/Keras

I want to classify images into either "Circle", "Square" or "Triangle". I have a directory containing 6 folders with each shape having a separate "shaded" or "unshaded" folder. How can I combine them into one category? For example: shaded and unshaded circles will be given a label "0" using flow_from_directory. I will then feed this into my CNN model and let it run.

Thanks for the help!

CodePudding user response:

classes in flow_from_directory needs to match the subdirectory names.

Example:

shapes
├── circle
│   ├── shared
│   └── unshared
├── square
│   ├── shared
│   └── unshared
└── triangle
    ├── shared
    └── unshared
import pathlib
# Get project root depending on your project structure.
PROJECT_ROOT = pathlib.Path().cwd().parent
SHAPES = PROJECT_ROOT / "shapes"

train_gen = ImageDataGenerator(
).flow_from_directory(
    directory=SHAPES, # the path to the 'shapes' directory.
    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),
    classes=["circle", "square", "triangle"],
    batch_size=8,
    class_mode="categorical",
)

Output:

Found 12 images belonging to 3 classes.
  • Related