1
1

More than 1 year has passed since last update.

[Python]10行以内で画像の背景を透過する

Posted at

tl;DR

上ツイートの受け売りです

やりたいこと

tst.png

この画像から背景を消して...

rembg_tst.png

こんな感じの画像を生成します。

前提

透過するわけなので、JPEGのようなアルファ値をもたないファイルは使えません。PNGなどに変換してください。

概要

rembgというライブラリを使用します。
画像を扱うためにPIL.Imageもインポートします。

from rembg import remove
from PIL import Image

rembgのremove()PIL.Imageのインスタンスを渡すことで背景を消してくれます。

in_path = 'tst.png'
out_path = f'rembg_{in_path}'

in_img = Image.open(in_path)
out_img = remove(in_img)

あとは処理された画像を保存すればOK。

out_img.save(out_path)
1
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
1
1