0
1

[Python3][Linux]画像サイズを一括変換する方法

Posted at

要 旨

Linux下においてPython3を使用して画像サイズを一括変換する方法について記述します。

実施要領

準備

作業用フォルダimage_resizeの作成

mkdir image_resize

作成したimage_resizeフォルダ内に入る。

cd image_resize

仮想環境venv構築

python -m venv .venv

仮想環境のアクティブ化を実施

source ./.venv/bin/activate

画像処理に便利なPIL(Python Image Library)をインストールする。

pip install pillow

画像サイズを320x320に一括変換する処理を含ませたpythonコードを作成する。
なお変換可能な画像の型式は、png、jpg、jpegである。

resize.py
from PIL import Image
import os

def resize_images(input_dir, output_dir, target_size=(320, 320)):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for filename in os.listdir(input_dir):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)

            img = Image.open(input_path)
            img_resized = img.resize(target_size)
            #img_resized = img.resize(target_size, Image.ANTIALIAS)
            img_resized.save(output_path)

#入力ディレクトリと出力ディレクトリを指定
input_directory = 'input_dir'
output_directory = 'output_dir'

resize_images(input_directory, output_directory)

変換したい画像を配置するinput_dirフォルダ及び変換先画像を格納するoutput_dirフォルダを作成する。

mkdir input_dir
mkdir output_dir

これで画像を一括変換する準備完了である。

画像サイズの一括変換実施要領

変換したい画像をinput_dirに配置する。
python3コードの実行

python resize.py

venvのアクティブ化を解除する。

deactivate

これでinput_dir内の画像が全て320x320のサイズに変換されてoutput_dirに格納される。
変換したい画像サイズが320x320以外の場合は、resize.pyファイルのtarget_size=(320, 320)の部分を適宜変更する。

結 言

今回は、Linux下においてPython3を使用して画像サイズを一括変換する方法について記述しました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1