Amazon 等平台要求商品主圖必須使用純白背景,Shopee、Lazada 和 TikTok Shop 上統一規格的正方形圖片也會讓商品頁顯得更專業。手工摳幾百張圖要花上好幾天。rembg 是一款開源工具,可以在普通 CPU 伺服器上執行 AI 摳圖模型。本文介紹如何安裝 rembg、對比各個模型,並用一個簡短的指令碼一次性把整個資料夾的商品照片處理成透明背景的 PNG 檔案和正方形白底 JPG 主圖。
apt install -y python3-venv
python3 -m venv /opt/rembg
/opt/rembg/bin/pip install "rembg[cpu,cli]"
/opt/rembg/bin/rembg --help
每個模型會在首次使用時自動下載並儲存到 ~/.u2net,因此首次執行時伺服器需要能訪問網際網路。
/opt/rembg/bin/rembg i photo.jpg cut-u2net.png # default model
/opt/rembg/bin/rembg i -m isnet-general-use photo.jpg cut-isnet.png # often cleaner edges
/opt/rembg/bin/rembg i -m birefnet-general photo.jpg cut-birefnet.png # most accurate, slower, more RAM
/opt/rembg/bin/rembg i -a photo.jpg cut-matting.png # alpha matting for hair and soft edges
從你的商品相簿中挑選五張典型照片,分別用候選模型處理,在原始尺寸下對比邊緣效果後再做選擇。
cat > /opt/rembg/whitebg.py <<'EOF2'
import os, sys
from PIL import Image, ImageOps
from rembg import new_session, remove
src, dst = sys.argv[1], sys.argv[2]
size = int(os.environ.get("SIZE", "1600")) # square canvas in pixels
fill = float(os.environ.get("FILL", "0.85")) # share of the canvas the product fills
session = new_session(os.environ.get("MODEL", "isnet-general-use"))
for sub in ("png", "white"):
os.makedirs(os.path.join(dst, sub), exist_ok=True)
for name in sorted(os.listdir(src)):
if not name.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
continue
base = os.path.splitext(name)[0]
img = ImageOps.exif_transpose(Image.open(os.path.join(src, name))).convert("RGB")
cut = remove(img, session=session)
box = cut.getchannel("A").getbbox()
if not box:
print(name, "no object found, skipped", flush=True)
continue
cut = cut.crop(box) # trim the empty space around the product
cut.save(os.path.join(dst, "png", base + ".png")) # transparent version
scale = size * fill / max(cut.size)
cut = cut.resize((max(1, round(cut.width * scale)), max(1, round(cut.height * scale))),
Image.Resampling.LANCZOS)
canvas = Image.new("RGB", (size, size), (255, 255, 255))
canvas.paste(cut, ((size - cut.width) // 2, (size - cut.height) // 2), cut)
canvas.save(os.path.join(dst, "white", base + ".jpg"), quality=92)
print(name, "done", flush=True)
EOF2
指令碼會自動校正手機照片的方向,去除背景,裁掉商品四周的空白,儲存一份透明 PNG,然後把商品居中放到純白(255, 255, 255)的正方形畫布上,使商品約佔畫面的 85%。
mkdir -p /data/photos/in /data/photos/out # upload the original photos to /data/photos/in
cd /data/photos
nohup /opt/rembg/bin/python /opt/rembg/whitebg.py in out > whitebg.log 2>&1 &
tail -f whitebg.log
# Other sizes or models, for example:
SIZE=2000 FILL=0.8 MODEL=birefnet-general /opt/rembg/bin/python /opt/rembg/whitebg.py in out
結果分別儲存在兩個資料夾中:out/png 存放透明背景的摳圖,可用於橫幅、廣告和設計;out/white 存放可直接上傳的正方形主圖。處理速度取決於模型和 CPU,建議先用 20 張照片計時,估算處理整個相簿需要多長時間。
remove() 呼叫中加上 alpha_matting=True,處理單張圖片時可使用 rembg i -a。這種方式速度較慢,只在必要時使用。不需要。每天處理幾十到幾百張圖片,CPU 伺服器完全夠用。只有每天要處理成千上萬張圖片,或長期使用最大的模型時,GPU 才會帶來明顯差別。
rembg 自帶一個小型 Web 服務(rembg s),提供簡單的網頁介面和 HTTP API。請讓它只監聽 127.0.0.1,再通過 Nginx 配置 HTTPS 和訪問密碼後對外提供,切勿直接開放在公網埠上。
多語言的商品標題、賣點和描述,請參閱 AI 批次生成多語言商品標題和描述;商品影片字幕,請參閱使用 faster-whisper 自動生成字幕。
如果按以上步驟操作後問題仍未解決,請提交工單聯絡 IMIDC 7×24 技術支援,並附上伺服器 IP、CPU 和記憶體配置、所用模型以及 whitebg.log 的最後幾行,方便工程師快速定位。