批量处理图像尺寸

import os
from PIL import Image
import cv2
import shutil

root = '图像路径'
save_path = '处理后的图像保存路径'
for r, d, files in os.walk(root):
    if files != []:
        for i in files:
            fp = os.path.join(r, i)
            label = i.split('_')[0]
            dst = os.path.join(save_path, label)
            if not os.path.exists(dst):
                os.makedirs(dst)

            img = Image.open(fp).convert('RGB')
            w, h = img.size
            if max(w, h) > 512:
                #要处理的图像尺寸,可修改
                img.thumbnail((512, 512), Image.ANTIALIAS)
                img.save(os.path.join(dst, i), quality=95, subsampling=0)
            else:
                shutil.copy(fp, os.path.join(dst, i))

猜你喜欢

转载自blog.csdn.net/hasque2019/article/details/121875138