Home > Software design >  save images in right files
save images in right files

Time:12-02

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)

in 'test_path' there are a lot of folders like 'A356_4_50_TS_167' and in this folder there are images named '0232-0024.jpg'. I want to save images in right place folder 'A356_4_50_TS_167' in 'processedex_path' folder. This code saves every changed images in every folder. Please help me to save images in right folders.

enter image description here

enter image description here

these are my original path and I want to save images in same named folder in 'test_ex'(=processedex_path) folder

enter image description here but every images from every folders were saved in each folders not 2 images per one folder but 70 images per on folder I want to save 2images per one folder

thank u for answering

CodePudding user response:

I can't run your code but I think you have too many for-loops

I would do

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)

  • Related