2021年12月11日土曜日

【Pillow】ImageOps.expandによる画像枠追加

画像処理ライブラリPillowのPIL.ImageOpsモジュールのImageOps.expandにより画像に枠を追加できる。
Pillow(PIL)を使うためにはインポートが必要。PIL.ImageOpsモジュールは通常以下の形式でインポートされる。

from PIL import ImageOps

例に用いる画像'city.jpg'は以下を使用(フリー写真素材ぱくたそより)。画像サイズは幅600高さ400ピクセル。






1. 書式

expand の書式は以下の通り。

PIL.ImageOps.expand(image, border=0, fill=0)
引数 意味
image 元画像
border 付け加える枠の幅をピクセルで指定。
fill 枠の色の指定。1つの値(グレースケール)または(R, G, B)のタプルで指定。デフォルトは0(黒)


2. expandの例

border=20として上下左右に20ピクセルの枠をつける例。画像サイズは枠が追加された分、(600,400)から(640,440)と増える。fillは指定していないのでデフォルトの黒となる。

from PIL import Image, ImageOps

im = Image.open('city.jpg')  
im_fit = ImageOps.expand(im, border=20)
im_fit.save('city_expand.jpg')

実行結果





fill=(0, 255, 255)として枠の色を黄色にする場合。

from PIL import Image, ImageOps

im = Image.open('city.jpg')  
im_fit = ImageOps.expand(im, border=20, fill=(0, 255, 255))
im_fit.save('city_expand.jpg')

実行結果





3. リファレンス

Pillow (PIL Fork) > ImageOps Module > PIL.ImageOps.expand(image, border=0, fill=0)

使用バージョン:Python 3.8.8 / Pillow 8.2.0

0 件のコメント:

コメントを投稿