(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
下采样原理
将2x2x3大小的图片缩小2倍,变成1x1x3的图片。像素值的变化是:将R、G、B三通道的2x2个像素值相加平均向上取整。以下图为例
R(30+79+20+52)/ 4 = 46
G (31+67+13+49) /4 =40
B (5+10+5+10) / 4 = 8