初めに
- 下記のrembgを利用して画像の背景を切り抜き異なる背景と合成するサンプルを作成する
https://github.com/danielgatis/rembg
インストール
pip install rembg
サンプルコード
from rembg import remove
from PIL import Image
# 背景を除きたい画像(人混みなどの画像はうまく切り出せない)
base_file = 'base.jpg'
backgroud_without_output_file = 'without_background.png'
base_image = Image.open(base_file)
output = remove(base_image)
output.save(backgroud_without_output_file)
# 背景画像を開く
background_path = 'backgroud.jpeg'
background = Image.open(background_path)
# 背景画像をリサイズ
background = background.resize(output.size, Image.ANTIALIAS)
# 合成
combined = Image.alpha_composite(background.convert('RGBA'), output)
# 結果を保存
combined_path = 'combined_image.png'
combined.save(combined_path)
実行結果
上記のコードで生成された画像

利用した画像
- 下記の画像を利用させて頂き検証しました。