2022年4月17日日曜日

【Pillow】ImageChops.offsetによる画像のオフセット処理

 画像処理ライブラリPillowのImageChops.offsetにより、オフセット値に応じて画像の中心がシフトし、はみ出た部分を反対側に貼り付けた新たな画像が生成される。

 Pillow(PIL)を使うためにはインポートが必要。PIL.ImageChopsモジュールは通常以下の形式でインポートされる。

from PIL import ImageChops

 またオフセット処理する画像 'game.jpg'(幅400ピクセルx高さ267ピクセル)は以下(フリー写真素材ぱくたそより)


'game.jpg'





1. ImageChops.offsetの書式

ImageChops.offsetの書式は以下

PIL.ImageChops.offset(image, xoffset, yoffset=None)
引数 意味
image 処理する画像
xoffset x軸方向のオフセット値(ピクセル)
xoffset y軸方向のオフセット値(ピクセル)。指定がない場合xoffsetと同じ値になる


2. 画像のオフセット処理

 offsetに100を指定した場合。xoffset,yoffsetどちらも100となり画像の中心が右下にシフトする。元の画像サイズからはみ出した個所は空白となった左上に貼り付けられる。

from PIL import Image, ImageChops

im = Image.open('game.jpg')
offset = ImageChops.offset(im, 100)

offset.save('offset_100.jpg')



 xoffsetに100、yoffsetに0を指定した場合。xoffsetのみなので画像の中心が右にシフトする。元の画像サイズからはみ出した個所は空白となった左に貼り付けられる。

from PIL import Image, ImageChops

im = Image.open('game.jpg')
offset = ImageChops.offset(im, 100, 0)

offset.save('offset_100_0.jpg')




3. リファレンス

Pillow (PIL Fork) > ImageChops (“Channel Operations”) Module > PIL.ImageChops.offset(image, xoffset, yoffset=None)

使用バージョン:Python 3.8.12 / Pillow 9.0.0

0 件のコメント:

コメントを投稿