在影像編輯器中逐點選取輪廓,去除產品照片或圖示素材的背景,相當耗時。rembg 是一套 Python 函式庫,使用深度學習模型 U2Net 識別影像的前景與背景,再將背景轉為透明並保留前景。我安裝了這套函式庫,並在網路中斷的狀態下測試背景去除功能。
rembg 使用名為 U2Net 的顯著物件偵測模型。它會識別影像中的主要主體,並以透明的 alpha 通道取代背景。rembg 專案採用 MIT License (*1)。
1. 安裝
FROM docker.io/library/python:3.12.13-slim
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir --quiet 'rembg[cpu]==2.0.76'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
# warmup_model.py (download the U2Net model during the build)
from rembg import new_session
new_session("u2net")
print("model downloaded ok")
podman build -t rembg-sandbox .
基本的 rembg 套件不包含推論引擎(onnxruntime),因此需要以 rembg[cpu] 安裝 CPU 推論的額外依賴。
2. 去除背景
我在測試環境中產生了一張由簡單形狀組成的合成影像,包含藍色背景和黃色圓形,並將它直接交給 rembg 處理。測試沒有使用外部影像。我在網路中斷的狀態下執行測試。
from PIL import Image, ImageDraw
from rembg import remove
img = Image.new("RGB", (400, 400), color=(40, 120, 200))
draw = ImageDraw.Draw(img)
draw.ellipse((100, 100, 300, 300), fill=(240, 200, 60))
img.save("/work/input.png")
with open("/work/input.png", "rb") as f:
output_bytes = remove(f.read())
with open("/work/output.png", "wb") as f:
f.write(output_bytes)
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work rembg-sandbox \
python remove_bg_demo.py
-v 選項讓容器可以讀寫指定的目錄。請在為實驗保留的空目錄中執行此指令。
為了確認 rembg 已去除背景,我將輸出的透明 PNG 影像合成到紅色背景上,並與原本的藍色背景比較。
整張影像的背景顏色都改變了。U2Net 在這張簡單的合成影像中識別出前景(圓形)與背景(色塊)之間的邊界,接著將背景轉為透明並保留圓形。透明區域占整張影像的 79.2%。圓形約占 19.6%,因此從整體扣除圓形後得到相同的數值。
讓機器決定邊界
去除背景時,選取輪廓的過程需要判斷主體在哪裡結束。rembg 讓模型做出這個判斷。由於 U2Net 將簡單形狀與背景分離,可以期待相同的機制也能分離真實照片的背景。
來源
*1 rembg (GitHub), https://github.com/danielgatis/rembg, MIT License