はじめに
rembg
というPythonライブラリを使って、画像の背景を透過する方法を紹介します。
インストール
pip install rembg
使い方
from rembg import remove
input_path = "input.png"
output_path = "output.png"
with open(input_path, "rb") as i:
with open(output_path, "wb") as o:
input = i.read()
output = remove(input)
o.write(output)
inputの画像はwebp等でも大丈夫です。
outputの画像は背景が透過された画像になりますので、png等で保存してください。
使ってみる
以下の画像を使ってみます。
元画像 | 透過後 |
---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
動物の画像はしっかり透過されていることがわかります。
コントラストが低めの画像が若干透過されていない部分があるのがわかります。
おわりに
ここまで簡単に背景透過できるのは便利ですね。