在电商运营或建站过程中,经常需要处理大量的商品图。如果手动一张张去除背景、改白底、调尺寸,不仅耗时而且费力。
本文将分享一段基于 Python 开源 AI 库 rembg 的自动化脚本:只需将图片放入文件夹并运行脚本,即可自动识别产品主体、去除杂乱背景、替换为纯白底色,并统一缩放至 800×800 像素,支持上千张图片一键批量处理。
一、 环境准备与依赖安装
在运行脚本前,请确保电脑已安装 Python,并在终端(Terminal / CMD)中安装以下核心依赖库:
pip install rembg pillow onnxruntimerembg:强大的开源 AI 抠图库,基于深度学习自动识别主体。
Pillow:Python 图像处理标准库,用于调整尺寸和合成白底。
二、 完整 Python 脚本代码
在你的图片存放文件夹中创建一个名为 remove_bg.py 的文件,用代码编辑器打开并写入以下完整代码:
import os
from PIL import Image
from rembg import remove
from io import BytesIO
# 获取当前脚本所在文件夹路径
current_dir = os.path.dirname(os.path.abspath(__file__))
output_dir = os.path.join(current_dir, "output")
os.makedirs(output_dir, exist_ok=True)
# 目标画布尺寸与商品填充比例
TARGET_SIZE = (800, 800)
PADDING = 0.90 # 0.90 表示商品占据画布的 90%,留白 10% 让产品更突出
for filename in os.listdir(current_dir):
# 支持常见的图片格式
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
img_path = os.path.join(current_dir, filename)
print(f"正在处理: {filename} ...")
try:
# 1. AI 智能抠图去背
with open(img_path, 'rb') as f:
no_bg_bytes = remove(f.read())
img_no_bg = Image.open(BytesIO(no_bg_bytes)).convert("RGBA")
# 2. 自动裁剪掉透明边缘,紧贴商品边界
bbox = img_no_bg.getbbox()
if bbox:
img_no_bg = img_no_bg.crop(bbox)
# 3. 计算等比例放大尺寸(让商品主体占满画布的 90%)
max_target_w = int(TARGET_SIZE[0] * PADDING)
max_target_h = int(TARGET_SIZE[1] * PADDING)
img_w, img_h = img_no_bg.size
ratio = min(max_target_w / img_w, max_target_h / img_h)
new_w = int(img_w * ratio)
new_h = int(img_h * ratio)
# 4. 高质量等比例缩放
img_resized = img_no_bg.resize((new_w, new_h), Image.Resampling.LANCZOS)
# 5. 创建 800x800 纯白画布并将产品居中对齐
white_bg = Image.new("RGBA", TARGET_SIZE, (255, 255, 255, 255))
x_offset = (TARGET_SIZE[0] - new_w) // 2
y_offset = (TARGET_SIZE[1] - new_h) // 2
white_bg.paste(img_resized, (x_offset, y_offset), img_resized)
# 6. 保存为高品质 JPG 格式到 output 文件夹
output_filename = os.path.splitext(filename)[0] + ".jpg"
output_path = os.path.join(output_dir, output_filename)
# 转换回 RGB 并保存
final_img = white_bg.convert("RGB")
final_img.save(output_path, "JPEG", quality=95)
except Exception as e:
print(f"处理文件 {filename} 时出错: {e}")
print("所有图片处理完成!请在 output 文件夹中查看结果。")三、 如何使用?
1. 将需要处理的产品图片(支持 JPG、PNG、WEBP)和 remove_bg.py 放在同一个文件夹内。
2.打开终端,进入该文件夹目录:
cd 文件夹路径3. 运行脚本:
python remove_bg.py处理完成后,文件夹内会自动生成一个名为 output 的新目录,里面就是处理好的 800×800 纯白底高清产品图。