Python, Pillowで画像の上下左右に余白を追加しサイズ変更

Posted: | Tags: Python, Pillow, 画像処理

ある画像を任意のサイズにしたいがアスペクト比(縦横比)を変えたりトリミングしたりしたくないという場合には、画像の上下左右に余白を追加してサイズを調節すればよい。

画像編集ソフトでキャンバスを拡大するイメージ。

Pythonの画像処理ライブラリPillow(PIL)のImageモジュールのメソッドpaste()でこれを実現する。

ここでは以下の内容について説明する。

  • 上下左右に任意の幅の余白を追加する
  • 長方形に余白を追加し正方形にする

Pillow(PIL)のインストール、基本的な使い方やトリミング(切り出し / 切り抜き)については以下の記事参照。

PILからImageをインポートし、元画像を読み込んでおく。

from PIL import Image

im = Image.open('data/src/astronaut_rect.bmp')

original image - astronaut

上下左右に任意の幅の余白を追加する

new()で単色無地の画像(ベタ画像)を生成し、paste()で元画像を貼り付けるという流れ。

以下の関数を定義。

引数top, right, bottom, leftに追加する余白の幅を指定、colorに余白の色を(R, G, B)(最大値は255)で指定する。

def add_margin(pil_img, top, right, bottom, left, color):
    width, height = pil_img.size
    new_width = width + right + left
    new_height = height + top + bottom
    result = Image.new(pil_img.mode, (new_width, new_height), color)
    result.paste(pil_img, (left, top))
    return result
source: imagelib.py

使ってみる。幅は適当。

im_new = add_margin(im, 50, 10, 0, 100, (128, 0, 64))
im_new.save('data/dst/astronaut_add_margin.jpg', quality=95)

astronaut add margin

長方形に余白を追加し正方形にする

長方形画像のアスペクト比(縦横比)を維持したまま短辺に余白を追加し正方形にする。

いちいち余白の幅を計算して指定するのは面倒なので、以下の関数を新たに定義。

def expand2square(pil_img, background_color):
    width, height = pil_img.size
    if width == height:
        return pil_img
    elif width > height:
        result = Image.new(pil_img.mode, (width, width), background_color)
        result.paste(pil_img, (0, (width - height) // 2))
        return result
    else:
        result = Image.new(pil_img.mode, (height, height), background_color)
        result.paste(pil_img, ((height - width) // 2, 0))
        return result
source: imagelib.py

使ってみる。

im_new = expand2square(im, (0, 0, 0))
im_new.save('data/dst/astronaut_expand_square.jpg', quality=95)

astronaut expand to square

サムネイルを作る場合など、決まったサイズの正方形にしたい場合は、余白を追加したあとresize()すればよい。

im_new = expand2square(im, (0, 0, 0)).resize((150, 150))

サムネイル画像作成についての詳細は以下の記事を参照。

関連カテゴリー

関連記事