應用場景與解決方案

AI 批次摳圖教程:用 rembg 批次去除商品圖片背景,生成透明 PNG 與白底主圖

5 個步驟 8 分鐘閱讀 23 次閱讀 0
本文目錄

Amazon 等平台要求商品主圖必須使用純白背景,Shopee、Lazada 和 TikTok Shop 上統一規格的正方形圖片也會讓商品頁顯得更專業。手工摳幾百張圖要花上好幾天。rembg 是一款開源工具,可以在普通 CPU 伺服器上執行 AI 摳圖模型。本文介紹如何安裝 rembg、對比各個模型,並用一個簡短的指令碼一次性把整個資料夾的商品照片處理成透明背景的 PNG 檔案和正方形白底 JPG 主圖。

只處理你自己擁有或已獲授權使用的圖片。上傳前請檢查處理效果:細線纜、透明玻璃、毛絨和頭髮是所有摳圖模型最難處理的情況。

步驟 1:安裝 rembg

apt install -y python3-venv
python3 -m venv /opt/rembg
/opt/rembg/bin/pip install "rembg[cpu,cli]"
/opt/rembg/bin/rembg --help

每個模型會在首次使用時自動下載並儲存到 ~/.u2net,因此首次執行時伺服器需要能訪問網際網路。

步驟 2:先用單張照片測試並選擇模型

/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
  • u2net:預設的通用模型。
  • isnet-general-use:速度相近,商品邊緣通常更乾淨利落,適合作為電商場景的預設選擇。
  • birefnet-general:處理複雜照片時最精確,但速度要慢好幾倍,記憶體佔用也更高。
  • u2netp:小巧快速的模型,適合快速預覽。

從你的商品相簿中挑選五張典型照片,分別用候選模型處理,在原始尺寸下對比邊緣效果後再做選擇。

步驟 3:建立批處理指令碼

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%。

步驟 4:批次處理整個資料夾

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 張照片計時,估算處理整個相簿需要多長時間。

步驟 5:檢查並修復難處理的圖片

  • 在深色背景上檢視 PNG 檔案:殘留的白邊光暈和被誤刪的部分,在深色背景上比在白色背景上容易發現得多。
  • 對於頭髮、毛絨和柔和邊緣,請對這些照片啟用 alpha matting 重新處理:在 remove() 呼叫中加上 alpha_matting=True,處理單張圖片時可使用 rembg i -a。這種方式速度較慢,只在必要時使用。
  • 模型會把陰影一併去除。如果希望商品下方保留自然的陰影,可以在設計工具中基於透明 PNG 自行新增。
  • 白色商品放在白色畫布上時,副圖可以考慮改用淺灰色背景;主圖要求請查閱各平台的規則。

常見問題

需要 GPU 嗎?

不需要。每天處理幾十到幾百張圖片,CPU 伺服器完全夠用。只有每天要處理成千上萬張圖片,或長期使用最大的模型時,GPU 才會帶來明顯差別。

同事不登入 SSH 也能使用嗎?

rembg 自帶一個小型 Web 服務(rembg s),提供簡單的網頁介面和 HTTP API。請讓它只監聽 127.0.0.1,再通過 Nginx 配置 HTTPS 和訪問密碼後對外提供,切勿直接開放在公網埠上。

AI 還能為商品上架自動完成哪些工作?

多語言的商品標題、賣點和描述,請參閱 AI 批次生成多語言商品標題和描述;商品影片字幕,請參閱使用 faster-whisper 自動生成字幕。

如果按以上步驟操作後問題仍未解決,請提交工單聯絡 IMIDC 7×24 技術支援,並附上伺服器 IP、CPU 和記憶體配置、所用模型以及 whitebg.log 的最後幾行,方便工程師快速定位。

這篇文章有幫助嗎?

相關教程