import glob import os from PIL import Image # 1、获取文件夹名称 path = r'H:\wordData\30train' dirnames = [f for f in os.listdir(path) if os.path.isdir(path + "\\" + f)] print(dirnames) def convertSize(jpgfile, outdir, width=112, height=112): # 将图片的大小的尺寸调整为112*112 img = Image.open(jpgfile) try: new_img = img.resize((width, height), Image.BILINEAR) if new_img.mode == 'P': new_img = new_img.convert("RGB") if new_img.mode == 'RGBA': new_img = new_img.convert("RGB") new_img.save(os.path.join(outdir, os.path.basename(jpgfile))) except Exception as e: print(e) # 2、遍历文件夹 for dir_name in dirnames: dir_path = path + "\\" + dir_name # 3、创建新文件夹 target_path = r"H:\wordData\new_30train" + "\\" + dir_name + "\\" if not os.path.exists(target_path): os.makedirs(target_path) # 4、遍历文件夹中的图片, 修改尺寸 for pic in os.listdir(dir_path): # 修改该文件夹下的图片 convertSize(dir_path + "\\" + pic, target_path) # 另存为的文件夹路径 print(dir_path + "文件夹下的图片处理完毕.\n") print("全部文件夹下的图片处理完毕.")
由于代码
new_img = img.resize((width, height), Image.BILINEAR)
参数 Image.BILINEAR 将被弃用,所以会报警告,不过不影响,在使用时可不加该参数。
标签:多个,img,Python,文件夹,new,path,os,dir From: https://www.cnblogs.com/ltkekeli1229/p/16843260.html