【问题标题】:save images in right files将图像保存在正确的文件中
【发布时间】:2022-01-07 21:37:35
【问题描述】:
path_school="/content/drive/MyDrive"

test_path=path_school+"//"+"test"
processedex_path=path_school+"//"+"test_ex"

for (path, dir, files) in os.walk(train_path):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        test_folder_list = [f for f in os.listdir(path_school+'//'+'test')] 
        for f in os.listdir(test_path):
          fol=os.path.splitext(f)[-1]
          '''
          os.makedirs(processedex_path+"//"+f)
          '''
        if ext == '.jpg':
            img=Image.open ("%s/%s" % (path, filename)).convert('L')
            img=img.resize((256,256))
            img.save(processedex_path+"//"+f+"//"+"pre"+"_"+filename)

'test_path' 中有很多像'A356_4_50_TS_167' 这样的文件夹,在这个文件夹中有名为'0232-0024.jpg'. 的图像 我想将图像保存在'processedex_path' 文件夹中的正确位置文件夹'A356_4_50_TS_167'。 此代码将每个更改的图像保存在每个文件夹中。 请帮我将图像保存在正确的文件夹中。

enter image description here

enter image description here

这些是我的原始路径,我想将图像保存在 'test_ex'(=processedex_path) 文件夹中的同名文件夹中

enter image description here 但是每个文件夹中的每张图像都保存在每个文件夹中,而不是每个文件夹 2 张图像,而是每个文件夹 70 张图像我想每个文件夹保存 2 张图像

谢谢你的回答

【问题讨论】:

  • 我不清楚,正确的路径是什么,“将每个更改的图像保存在每个文件夹中”是什么意思
  • 也许首先使用print() 来查看变量中的内容以及执行了哪部分代码。它被称为"print debuging"
  • 你使用了os.walk 和两次os.listdir() - 也许你有太多的for-loops。至于我,你应该只使用一个os.lisdir'test_path'

标签: python image directory save


【解决方案1】:

我无法运行你的代码,但我认为你有太多 for-loops

我愿意

import os
from PIL import Image

path_school = "/content/drive/MyDrive"

# source & destination folder
test_path        = os.path.join(path_school, "test")
processedex_path = os.path.join(path_school, "test_ex")

os.makedirs(processedex_path, exist_ok=True)

for subfolder in os.listdir(test_path):
    
    # source & destination subfolder
    src_subfolder = os.path.join(test_path, subfolder)
    dst_subfolder = os.path.join(processedex_path, subfolder)

    if os.path.isdir(src_subfolder):  # check if it is really subfolder

        os.makedirs(dst_subfolder, exist_ok=True)
                    
        for filename in os.listdir(src_subfolder):
            if filename.lower().endswith( ('.jpg', '.png', 'webp') ):
                # source & destination file
                src_file = os.path.join(src_subfolder, filename)
                dst_file = os.path.join(dst_subfolder, "pre_"+filename)
                    
                img = Image.open(src_file).convert('L')
                img = img.resize((256, 256))
                img.save(dst_file)

                print('converted:', filename)
                print('src:', src_file)
                print('dst:', dst_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 2018-06-12
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2013-10-14
    相关资源
    最近更新 更多