【python】rembg一键替换证件照背景-bysking

315 阅读1分钟
  • 安装基本的python环境 (略)
  • 安装rembg
pip install rembg
  • 新建.py文件,贴入下面代码
from rembg import remove
from PIL import Image
import numpy as np
import io

def remove_background_and_set_white(input_path, output_path):
    # 读取输入图像
    with open(input_path, 'rb') as i:
        input_data = i.read()
    
    # 使用 rembg 移除背景
    output_data = remove(input_data)
    
    # 将输出数据转换为 PIL Image 对象
    image = Image.open(io.BytesIO(output_data))
    
    # 创建一个白色背景
    white_background = Image.new('RGBA', image.size, (255, 255, 255, 255))
    
    # 将原图粘贴到白色背景上
    white_background.paste(image, (0, 0), image)
    
    # 转换为 RGB 模式(去除 alpha 通道)
    final_image = white_background.convert('RGB')
    
    # 保存结果
    final_image.save(output_path)

# 使用示例
input_path = './zjz.jpeg'
output_path = 'output_white_bg.jpg'
remove_background_and_set_white(input_path, output_path)
  • 看下效果

image.png

image.png