Search code examples
pythonloopsmachine-learningclassificationglob

Python: store image and associated folder name in a list


I am very new to Python and I was wondering if someone could help me with this problem.

I have a folder "Train" with sub-folders "ball", "chair", "cup", "bag" each sub-folder consists of it associated image.Such as:

project/Train/ball/01.jpg
project/Train/chair/02.jpg
project/Train/cup/03.jpg
project/Train/bag/04.jpg

I have written the following code to read image from Train

names_path = []
training_paths = []

for name in glob.glob('/Train/**/*.jpg'):
    img = cv2.imread(name)
    training_paths.append(name)

For names_path = [] I would like to store the name of the sub-folder (bag, chat, cup, ball) of the current image. So if first image in the loop belongs to ball, save image path to training_paths and "ball" to names_path

I have tried using another loop such as

for clas in glob.glob('/Train/*/'):

But when I check the list all the entries are None.


Solution

  • If file_path ist the path of your image you can get the directory name with:

    from os import path
    file_path = "project/Train/ball/01.jpg"
    dir_name = path.basename(path.dirname(file_path))  # "ball"