カテゴリー
D-Studio プログラム

画像リサイズ

Pythonで画像一括リサイズ!

今回は縦長や横長の画像を正方形にリサイズ。余白部分はそのサイズの白色画像を合成。

画像サイズ指定された時に一気に変更かけられうので便利!

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import glob
import os.path
import cv2
from PIL import Image


#-------------------------------------------------
## main ###
#-------------------------------------------------
if __name__=='__main__':

    #
    path = "/画像置いてるパス/*"
    bgpath = "/白色正方形画像/bg.png"

    # リサイズしたい長い辺のサイズ
    re_length = 1024


    files = glob.glob(path)
    cnt = 1
    for file in files:
        # 拡張子取得
        root, ext = os.path.splitext(file)
        # .jpegだけ表示
        if ext == ".jpeg":
            #name = str(cnt).zfill(4)
            name = basename_without_ext = os.path.splitext(os.path.basename(file))[0]
            path = path.rstrip("*")

            img2 = cv2.imread(file)
            h, w = img2.shape[:2]

            # 変換する倍率を計算
            re_h = re_w = re_length / max(h, w)

            # アスペクト比を固定して画像を変換
            img_res = cv2.resize(img2, dsize=None, fx=re_h, fy=re_w)
            h2, w2 = img_res.shape[:2]

            # 1024x1024の正方形の画像にまとめる。余白は白色
            img1 = img_res
            img_base = cv2.imread(bgpath)

            height, width = img1.shape[:2]
            if height == re_length:
                img_base[0:height, int((re_length-width)/2):width + int((re_length-width)/2)] = img1
            else:
                img_base[int((re_length-height)/2):height + int((re_length-height)/2), 0:width] = img1

            out_dir = path + "resize/"
            if not os.path.exists(out_dir):
                # ディレクトリが存在しない場合、ディレクトリを作成する
                os.makedirs(out_dir)

            cv2.imwrite(out_dir + name+".jpeg", img_base)

        cnt = cnt + 1

今回はCV2を利用してます。

JPGとかPNGはこれで簡単にいけます。

リサイズ時の余白用白色画像は適当に用意してリサイズして利用するのも可能。(今回は1024×1024用意してます)