简体   繁体   中英

Python Pillow Library opening and editing images ending with specific names

Currently I am using Python Pillow Library to edit images. Since I am dealing with large data-sets and need to edit some images with only specific name endings (say only image names that end with cropped or images of specific file type like png or bmp), is there a way to write code in such a way that allows me to open and edit these images? If so please give me hints or suggestions! Thanks!

Also Pillow version is 5.0.0 and Python version is 3.6.

If your question is to only know if is there a way to write code to only allow you to edit image files with specific file type and specific end names. Then the answer is YES . You can do it with python.

A Sample Code:

import os
from PIL import Image #Pillow

directory = os.fsencode("images_folder")
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".png") or filename.endswith(".bmp") or "cropped" in filename: 
        # Do the editing using pillow
        # img = Image.open(filename)
        continue

Certainly you can do this in python, but the specific way of doing this obviously depends on the specifics of the problem. Are all your images stored in one directory or many? Will you be running the script from the same directory as the images or from some other directory? Etc.

To get you started, take a look at the os module here .

In this module, there is a listdir method that returns a list of all files inside a directory. You can iterate through that list and find all the filenames that ends with a specific set of characters by using the built in endswith method on strings. For example:

    import os

    fileslist = [f for f in os.listdir(path) if f.endswith('.jpg')]

Now that you have a filelist of all the files in a directory that ends with some certain characters, you can then use pillow to open the images from that list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM