简体   繁体   中英

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

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, ie 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

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM