How to save processed images to different folders within a folder in python?

4k Views Asked by At

I have code with looks through a folder 'Images' and then subfolders and processes all those images.

I now need to save those images to a parallel directory, i.e. a folder called 'Processed Images' (in same directory as 'Images' folder) and then to the subfolders within this folder - these subfolders are named the same as the subfolders in 'Images' - the image should save to the same name of subfolder that it came from.

I can get the images to save to 'Processed Images' but not the subfolders within it.

path = ("...\\Images")

for dirName, subdirList, fileList, in os.walk(path):

    for file in fileList:

        full_file_path = os.path.join(dirName, file)

        if file.endswith((".jpg")):

        image_file = Image.open(full_file_path)

        image_file = image_file.convert('L')

        image_file = PIL.ImageOps.invert(image_file)

        image_file = image_file.resize((28, 28))

        new_filename = file.split('.jpg')[0] + 'new.png'

        path2 = ("...\\Processed Images")

        image_file.save(os.path.join(path2, new_filename))

    else: continue
2

There are 2 best solutions below

0
On

You can use the function os.mkdir() to create a new folder. dirName returned by os.walk() gives you the current folder path, so you can just extract the part of the path that you need, append it to ...\\Processed Images and create the new folder if needed.

Be sure to use two separate folder trees for the input files and output files. Otherwise os.walk() will find the new directories with the output images and continue to iterate over them.

0
On

I think you can seriously simplify this code using pathlib. I’m not sure about the triple dots (I think they should be double) in your base paths but they may work for you.

    from pathlib import Path
    path = Path("...\\Images")
    path2 = Path("...\\Processed Images")
    path2.mkdir(exist_ok=True)

    for jpg_file in p.glob('**/*.jpg'):
        full_file_path = str(jpg_file)
        image_file = Image.open(full_file_path)
        image_file = image_file.convert('L')
        image_file = PIL.ImageOps.invert(image_file)
        image_file = image_file.resize((28, 28))

        new_filename = jpg_file.stem + 'new.png'
        image_file.save(str(path2 / new_filename))