You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Mask实现图像透明背景(当前生成白色背景)

实现透明背景的图像抠图修改方案

你现在的代码是把背景替换成了白色,要实现类似removebg的透明背景效果,核心是给图像加上Alpha通道,用matte(遮罩)来控制每个像素的透明度。以下是修改后的代码:

from PIL import Image
import numpy as np

def combined_display(image, matte):
    # 计算显示分辨率
    w, h = image.width, image.height
    rw, rh = 800, int(h * 800 / (3 * w))
    
    # 处理原图像为RGB格式
    image = np.asarray(image)
    if len(image.shape) == 2:
        image = image[:, :, None]
    if image.shape[2] == 1:
        image = np.repeat(image, 3, axis=2)
    elif image.shape[2] == 4:
        image = image[:, :, 0:3]
    
    # 把matte转成Alpha通道(0全透明,255完全不透明)
    matte = np.asarray(matte)
    # 确保matte是单通道
    if len(matte.shape) == 3 and matte.shape[2] == 3:
        matte = matte[:, :, 0]
    alpha = (matte / 255 * 255).astype(np.uint8)
    alpha = alpha[:, :, None]  # 调整为(H,W,1)的形状,方便和RGB合并
    
    # 合并RGB和Alpha通道,生成带透明信息的RGBA图像
    rgba_image = np.concatenate([image, alpha], axis=2)
    
    # 转成PIL图像并保存,PNG格式天然支持透明背景
    foreground = Image.fromarray(rgba_image)
    foreground.save("imag.png", format="png")
    # 可选:调整尺寸用于预览显示
    foreground = foreground.resize((rw, rh), Image.Resampling.LANCZOS)
    return foreground

关键修改点:

  • 删掉了原来生成白色背景的代码,不再用image * matte + 白色背景的方式,直接保留原图像的RGB内容
  • 将matte处理成单通道的Alpha值,作为图像的透明通道,遮罩里的白色区域对应不透明,黑色区域对应透明
  • 把RGB和Alpha通道合并成RGBA格式,PIL保存PNG时会自动保留透明信息,这样输出的图片背景就是透明的

输入示例图:(一张带有背景的人物图片)

内容的提问来源于stack exchange,提问作者vijish madhavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:45:36