批量放縮(下采樣)

(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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章