pythonpython-3.xpython-imaging-library

Run the code where given path have multiple subfolders and same code to be apply for cropping images using PIL python


I have a 5000 multiple folders in one folder i.e test, each folder has 2-3 images, I need to crop the images, currently my code is for applying single folder for crop the images, is there any alternate option where multiple folders can apply for the same code.

Here is my code

from PIL import Image
import os.path, sys
path = r"D:\test"
dirs = os.listdir(path)

def crop():
    for item in dirs:
        fullpath = os.path.join(path,item)         
        if os.path.isfile(fullpath):
            im = Image.open(fullpath)
            f, e = os.path.splitext(fullpath)
            imCrop = im.crop((80, 270, 4000, 3000)) 
            imCrop.save(f + 'Cropped.jpg', "JPEG")
crop()

enter image description here


Solution

  • You could use os.walk to recursively walk through all dirs:

    from PIL import Image
    import os
    
    root_dir = r"D:\test"
    
    def crop_image(image_path):
        try:
            with Image.open(image_path) as im:
                im_crop= im.crop((80,270,4000,3000)) 
                file_name,ext =os.path.splitext(image_path)
                cropped_image = file_name+'_Cropped.jpg'
                im_crop.save(cropped_image,"JPEG")
        except Exception as e:
            print(f"Error {image_path}:{e}")
    
    def crop_images_in_folders(root_folder):
        for folder_name,subfolders,filenames in os.walk(root_folder):
            for filename in filenames:
                full_image_path = os.path.join(folder_name,filename)
                if filename.lower().endswith(('.jpg','.jpeg', '.png')):
                    crop_image(full_image_path)
    
    
    crop_images_in_folders(root_dir)