简体   繁体   English

如何将处理后的图像保存到python文件夹中的其他文件夹中?

[英]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. 现在,我需要将这些图像保存到一个并行目录中,即一个名为“ Processed Images”的文件夹(与“ Images”文件夹位于同一目录),然后再保存到该文件夹​​中的子文件夹-这些子文件夹的名称与“图片”-图片应保存为与该图片相同的子文件夹名称。

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. 您可以使用函数os.mkdir()创建一个新文件夹。 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. os.walk()返回的dirName为您提供当前文件夹路径,因此您只需提取所需路径的一部分,将其追加到...\\\\Processed Images并在需要时创建新文件夹。

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. 否则, os.walk()将找到包含输出图像的新目录,并继续对其进行迭代。

I think you can seriously simplify this code using pathlib . 我认为您可以使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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