Python/PIL Resize all images in a folder

后端 未结 8 1275
感动是毒
感动是毒 2020-12-08 00:31

I have the following code that I thought would resize the images in the specified path But when I run it, nothing works and yet python doesn\'t throw any error so I don\'t

8条回答
  •  清歌不尽
    2020-12-08 01:33

    Heavily borrowed the code from @Sanjar Stone. This code work well in Windows OS. Can be used to bulky resize the images and assembly back to its corresponding subdirectory.

    Original folder with it subdir:
    ..\DATA\ORI-DIR
    ├─Apolo
    ├─Bailey
    ├─Bandit
    ├─Bella
    

    New folder with its subdir:

    ..\DATA\NEW-RESIZED-DIR
    ├─Apolo
    ├─Bailey
    ├─Bandit
    ├─Bella
    

    Gist link: https://gist.github.com/justudin/2c1075cc4fd4424cb8ba703a2527958b

    from PIL import Image
    import glob
    import os
    
    # new folder path (may need to alter for Windows OS)
    # change path to your path
    ORI_PATH = '..\DATA\ORI-DIR'
    NEW_SIZE = 224
    PATH = '..\DATA\NEW-RESIZED-DIR' #the path where to save resized images
    
    # create new folder
    if not os.path.exists(PATH):
        os.makedirs(PATH)
    
    # loop over existing images and resize
    # change path to your path
    for filename in glob.glob(ORI_PATH+'**/*.jpg'): #path of raw images with is subdirectory
        img = Image.open(filename).resize((NEW_SIZE,NEW_SIZE))
        
        # get the original location and find its subdir
        loc = os.path.split(filename)[0]
        subdir = loc.split('\\')[1]
        
        # assembly with its full new directory
        fullnew_subdir = PATH+"/"+subdir
        name = os.path.split(filename)[1]
        
        # check if the subdir is already created or not
        if not os.path.exists(fullnew_subdir):
            os.makedirs(fullnew_subdir)
        
        # save resized images to new folder with existing filename
        img.save('{}{}{}'.format(fullnew_subdir,'/',name))
    

提交回复
热议问题