(1) 等比例放縮
from PIL import Image
import os
scale = 1.0/3
cnt=1
source_path=r"C:\Users\HD"
result_path=r"C:\Users\tresult"
files = os.listdir(source_path)
files.sort(key=lambda x: int(x.split('.')[0]))
for file in files:
img = Image.open(os.path.join(source_path,file))
width = int(img.size[0] * scale)
height = int(img.size[1] * scale)
img_resize = img.resize((width,height),Image.ANTIALIAS)
img_resize.save(os.path.join(result_path,"%d.png" %cnt))
cnt = cnt+1
(2)放縮爲指定大小(裁剪)
from PIL import Image
import os
cnt = 0
source_path=r"C:\Users\Desktop\Urban100"
result_path=r"C:\Users\Desktop\Urban100"
files = os.listdir(source_path)
files.sort(key=lambda x: str(x.split('.')[0]))
for file in files:
img = Image.open(os.path.join(source_path,file))
width = int(img.size[0])
height = int(img.size[1])
if width%3==1:
width = width-1
if width%3==2:
width = width-2
if height%3==1:
height = height-1
if height%3==2:
height = height-2
img_resize = img.resize((width,height),Image.ANTIALIAS)
img_resize.save(os.path.join(result_path,"%d.png" %cnt))
cnt = cnt + 1