Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I edit all images inside of a directory with python with pillow?

I have some images with 24 bit depth that I should convert them to 8 bit depth.
So I can do it for one image but for multiple images I get this error :

 a=img.convert("P", palette=Image.ADAPTIVE, colors=8)
AttributeError: 'list' object has no attribute 'convert'

image:image

I tried this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from PIL import Image
import os
os.chdir('D:\\background')
img=os.listdir()
a=img.convert("P", palette=Image.ADAPTIVE, colors=8)
a.save('D:\\test')
 

So if I want to convert multiple files with pillow how should I do it?

>Solution :

Check documentation here https://pillow.readthedocs.io/en/stable/reference/Image.html

img=os.listdir(), and img is a list of filenames under the folder ‘D:\background’. Here’s my implementation:

from PIL import Image
import os

base_dir_src = 'D:\\background'
base_dir_dst = 'D:\\test'
os.chdir()
for filename in os.listdir():
    with Image.open(filename) as img:
        converted_img = img.convert("P", palette=Image.ADAPTIVE, colors=8)
        converted_img.save(os.path.join(base_dir_dst, filename))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading