批量将图像转换为统一大小尺寸
由于图像大小经常不一致,因此有必要将其转换为同一大小的尺寸,便于图像的后续操作。
#导入包
from PIL import Image
import os.path
import glob
#定义批量转换函数
def convertjpg(jpgfile,outdir,width=500,height=500): #默认转换后的尺寸为宽500,高500,读者可自定义大小
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)
for jpgfile in glob.glob("G:/.../*.jpg"): #图像数据的路径,图像格式为jpg格式,读者可自行更改为png,jepg等格式
# print(jpgfile)
convertjpg(jpgfile,"G:/...") #需保存的路径
参考博客:
https://blog.csdn.net/lovetaozibaby/article/details/84860507?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase