获取一个图像目录并调整目录中所有图像的大小

rza*_*atx 5 python image image-resizing python-3.7

我正在尝试将高分辨率图像转换为更易于机器学习管理的图像。目前,我有代码可以将图像大小调整为我想要的高度和宽度,但是我必须一次处理一张图像,当我只处理 12-24 个图像时,这还不错,但很快我想放大做几百张图像。我正在尝试读取目录而不是单个图像并将新图像保存在新目录中。初始图像可能会有所不同,如 .jpg、.png、.tif 等,但我希望将所有输​​出图像设为 .png,就像我在代码中那样。

import os
from PIL import Image

filename = "filename.jpg"
size = 250, 250
file_parts = os.path.splitext(filename)

outfile = file_parts[0] + '_250x250' + file_parts[1]
try:
    img = Image.open(filename)
    img = img.resize(size, Image.ANTIALIAS)
    img.save(outfile, 'PNG')
except IOError as e:
    print("An exception occured '%s'" %e)
Run Code Online (Sandbox Code Playgroud)

任何有关此问题的帮助将不胜感激。

Mit*_*lin 2

您可以使用循环遍历目录的内容

import os

for root, subdirs, files in os.walk(MY_DIRECTORY):
    for f in files:
        if f.endswith('png'):
            #do something 
Run Code Online (Sandbox Code Playgroud)