Python|批处理产品图片背景

需求示例:
1,识别原图中的产品主体,去除背景并将背景色设定为白色。
2,同时统一图片尺寸为800X800像素

如果有数百甚至上千张图片,使用 Python 开源库 ⁠rembg⁠ 是效率最高且完全免费的方案。

第一步:
在图片所在文件夹新建记事本,文件名称保存为

remove_bg.py

第二步:右键用记事本打开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 表示留 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} ...")
        
        # 1. 扣除背景
        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. 保存导出
        final_img = white_bg.convert("RGB")
        save_path = os.path.join(output_dir, os.path.splitext(filename)[0] + "_800x800.jpg")
        final_img.save(save_path, quality=95)
        print(f"成功导出大主体 800x800 图: {filename}")

print("\n全部处理完成!")

第三步:命令提示符Win + R),输入 cmd, 回车
输入以下代码。加载rembg库。

python -m pip install rembg pillow

第四步:在命令行中,先用 ⁠cd⁠ 命令切换到图片所在的文件夹:以所在文件夹“下载”为例。

cd C:\Users\Downloads\remove

第五步:运行python脚本

python remove.py

第一次启动 AI 模块时,⁠rembg⁠ 会在后台自动从 GitHub 下载 AI 模型库(文件大小约 170MB)
程序执行完成后,会在新创建的子文件夹(output)
中显示尺寸为800的纯白背景正方形图片文件。

※ 如果运行出现以下报错代码,意味着缺少了 ⁠rembg⁠ 依赖的核心推理引擎 ⁠onnxruntime⁠。

No onnxruntime backend found.
Please install rembg with CPU or GPU support:

    pip install "rembg[cpu]"  # for CPU
    pip install "rembg[gpu]"  # for NVIDIA/CUDA GPU

For more information, see: https://github.com/danielgatis/rembg#installation

C:\Users\Downloads\remove>

直接运行以下命令补全安装 CPU 支持即可:

python -m pip install "rembg[cpu]"