如何提取图片背景并保存?能否将移除的背景存储为PNG格式?
使用rembg保存移除的背景为PNG格式
当然可以,你可以通过rembg的掩码功能提取并保存移除的背景为PNG格式。具体做法是利用remove函数的only_mask=True参数获取前景/背景的掩码,再结合原图生成背景图:
from rembg import remove from PIL import Image import numpy as np input_path = 'input.png' foreground_path = 'foreground.png' background_path = 'background.png' # 打开原图并转为RGBA格式(支持透明通道) input_img = Image.open(input_path).convert("RGBA") # 生成并保存移除背景后的前景图 foreground = remove(input_img) foreground.save(foreground_path) # 获取背景掩码:返回灰度图,白色区域为前景,黑色区域为背景 mask = remove(input_img, only_mask=True) mask_np = np.array(mask) # 将原图转为numpy数组方便像素级操作 input_np = np.array(input_img) # 创建背景图:把原图中属于前景的区域设为透明,保留背景区域的像素 background_np = input_np.copy() # 掩码中白色(255)的部分对应前景,将这些区域的alpha通道设为0(完全透明) background_np[mask_np == 255, 3] = 0 # 转回PIL图像并保存为PNG background = Image.fromarray(background_np) background.save(background_path)
这段代码会生成两个文件:foreground.png是移除背景后的前景图,background.png是提取出的背景图(前景区域为透明),正好满足你对比图片背景的需求。
内容的提问来源于stack exchange,提问作者Mikee
相关产品推荐
相关产品推荐

