Search code examples
pythonpython-imaging-libraryos.path

How to save images with the same name to the different direction using PIL and os.path?


While trying to split the path to get a name, I get the traceback: TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)

Solution

  • By the code above you will get image in thumbnails I recommend to use resize function because from resize you can maintain you aspect ratio that helps you in getting better results.

    image.thumbnail((640, 428), Image.ANTIALIAS)
    

    this line of code is converting your thumbnail.which is not good approach of resizing. Try the code below.

    import os
    from PIL import Image
    
    PATH = "F:\\FYP DATASET\\images\\outliers Dataset\\Not Outliers\\"
    Copy_to_path="F:\\FYP DATASET\\images\\outliers Dataset\\"
    
    for filename in os.listdir(PATH):
        img = Image.open(os.path.join(PATH, filename)) # images are color images
        img = img.resize((224,224), Image.ANTIALIAS)
        img.save(Copy_to_path+filename+'.jpeg') 
    

    In this code you are taking images directly from folder resize them and saving them to other location with same name. All the images are processing one by one So you need not worry to load all the images at once into the memory.