likes
comments
collection
share

随笔-Python批量调整图片大小

作者站长头像
站长
· 阅读数 3

随笔-Python批量调整图片大小

参考文档:

自己的数据集比较凌乱,图片大小不一,可以通过Python批量来调整图片大小为统一尺寸,方便训练。

import os
from PIL import Image


def resize(old_path, new_path, size, resample):
    """ 
     通过指定的resample方式调整old_path下所有的jpg图片为指定的size,并保存到new_path下 
    """
    if os.path.isdir(old_path):
        for child in os.listdir(old_path):

            if child.find('.jpg') > 0:
                im = Image.open(old_path + child)
                im_resized = im.resize(size=size, resample=resample)
                if not os.path.exists(new_path):
                    os.makedirs(new_path)
                print(child, 'resize successfully!')
                im_resized.save(new_path + child, im.format)
            child_path = old_path + child + '/'

            resize(child_path, new_path, size, resample)


if __name__ == "__main__":
    old_path = './test_dataset/'
    new_path = './test_dataset_train/'
    size = (1280, 720)
    resample = Image.BILINEAR # 使用线性插值法重采样
    resize(old_path, new_path, size, resample)