画像の解像度を一括でリサイズしたいことがあったのでスクリプトを作成しました。

環境

  • python3系
  • Pillow

準備

基本はデフォで入ってるものでできますが、画像を扱いやすくするPillowを使いましょう

mkdir images resized_images
pip install Pillow

画像ディレクトリの構成としては

|--images/ (画像がたまってるディレクトリ )
|--resized_images/ (リサイズした画像を入れるディレクトリ )

コード

target_size の値を適宜調整すると
よしなに調整できるはずです

デフォでは横幅を合わせる形でやってますが
コード少しいじれば縦に合わせることもできるはずです。

import os
import glob
from PIL import Image

files = glob.glob('./images/*')
target_size = 500

for f in files:
    file_name = f.split('./images/')[1]
    
    try:
        img = Image.open(f)
        if img.width < 10:
            # 破損した画像の時はスキップ
            continue

        if img.width < target_size:
            # そんなに大きくない画像の時はそのまま保存
           img.save(f'./resized_images/{file_name}')
           print(f'{file_name} : is already small Done! [{img.width}, {img.height}]')
           continue

        # でかい画像はリサイズして保存
        div_ratio = img.width / target_size
        img_resize = img.resize((int(img.width / div_ratio), int(img.height / div_ratio)))
        img_resize.save(f'./resized_images/{file_name}')
        print(f'{file_name} : resize Done! [{img_resize.width}, {img_resize.height}]')

    except:
        print(f'{f} could not open')