主流 Python 图像抠图模型的介绍、安装、代码示例与适用场景。共计 15 个模型/库。
https://github.com/danielgatis/rembghttps://github.com/xuebinqin/U-2-Net
rembg 是目前 Python 生态中最流行的背景移除库。底层基于 U²-Net 深度学习模型,能自动识别图像主体并移除背景,无需手动标记(trimap-free)。2023 年发布后迅速在 GitHub 斩获 15k+ stars,原因是安装即用、API 极简——两行代码出结果。提供命令行、Python API、HTTP 服务端等多种使用方式,是整个抠图生态中社区最繁荣的工具。
U²-Net 的核心架构是一个嵌套的 U 形网络(nested U-structure),在显著目标检测(SOD)任务上表现优异,能捕捉到细节边缘(如头发丝)。它也是后来许多抠图模型(包括 RMBG 早期版本)的底层基础。
pip install rembg首次运行时会自动下载模型文件(~176MB),存储在 ~/.u2net/ 目录。
from rembg import removefrom PIL import Image# 读取输入图像input_img = Image.open("photo.jpg")# 移除背景 —— 一行搞定output_img = remove(input_img)# 保存透明背景结果output_img.save("photo_no_bg.png")rembg i photo.jpg photo_no_bg.pnghttps://github.com/ZHKKKe/MODNet
MODNet 是商汤科技(SenseTime)提出的轻量级实时人像抠图模型,专为实时应用和移动端部署设计。与 U²-Net 不同,MODNet 聚焦于人像领域,在头发丝、半透明衣物等细节上表现更优。支持一键导出 ONNX 格式,可在移动端和 Web 端部署。
核心优势:轻量、快速、人像边缘精细。输入 512×512 的图像,CPU 上也能在 1 秒内完成推理。模型仅 25MB,是移动端和实时视频流的首选方案。
pip install onnxruntime pillow numpy opencv-python# 下载预训练模型wget https://github.com/ZHKKKe/MODNet/releases/download/v1.0/modnet_photographic_portrait_matting.onnximport onnxruntimeimport numpy as npfrom PIL import Image# 加载 ONNX 模型session = onnxruntime.InferenceSession("modnet_photographic_portrait_matting.onnx")defmodnet_remove_bg(img_path, output_path, size=(512, 512)):"""MODNet 人像背景移除""" img = Image.open(img_path).convert("RGB") orig_w, orig_h = img.size# 预处理:缩放到模型输入尺寸 img_resized = img.resize(size, Image.BICUBIC) img_np = np.array(img_resized).astype(np.float32) img_np = img_np.transpose(2, 0, 1) / 255.0# CHW 格式 + 归一化 img_np = np.expand_dims(img_np, axis=0)# 推理:输出 alpha 遮罩 inputs = {session.get_inputs()[0].name: img_np} alpha = session.run(None, inputs)[0][0, 0]# 还原到原始尺寸 alpha = Image.fromarray((alpha * 255).astype(np.uint8)) alpha = alpha.resize((orig_w, orig_h), Image.BICUBIC)# 合成透明背景 img = img.resize((orig_w, orig_h)) img.putalpha(alpha) img.save(output_path)modnet_remove_bg("portrait.jpg", "portrait_no_bg.png")https://github.com/facebookresearch/segment-anything
Meta 在 2023 年发布的通用分割基础模型,在 1100 万张图像的 10 亿个掩码上训练。SAM 不是专门的抠图模型,但它能分割图像中的任何物体——给定一个点、框或文本提示,就能精确分割出目标。这使得它在抠图任务上有极高的灵活性:你不需要它"自动"找到前景,而是可以告诉它前景是什么。
需要安装官方 segment-anything 库并下载模型(ViT-H 版本 ~2.4GB)。
pip install git+https://github.com/facebookresearch/segment-anything.gitpip install opencv-python pillow torch torchvision# 下载模型:https://github.com/facebookresearch/segment-anything#model-checkpointsimport cv2import torchimport numpy as npfrom PIL import Imagefrom segment_anything import sam_model_registry, SamAutomaticMaskGenerator# 加载模型sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")sam.to("cuda"if torch.cuda.is_available() else"cpu")# 自动生成所有掩码mask_generator = SamAutomaticMaskGenerator(sam)image = cv2.imread("photo.jpg")image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)masks = mask_generator.generate(image_rgb)# 取面积最大的掩码作为"主体"largest_mask = max(masks, key=lambda x: x["area"])# 应用到原图result = Image.fromarray(image_rgb).convert("RGBA")alpha = Image.fromarray((largest_mask["segmentation"] * 255).astype(np.uint8))result.putalpha(alpha)result.save("photo_sam_bg.png")from segment_anything import SamPredictorpredictor = SamPredictor(sam)predictor.set_image(image_rgb)h, w = image_rgb.shape[:2]input_point = np.array([[w // 2, h // 2]])input_label = np.array([1]) # 1 = 前景masks, scores, _ = predictor.predict( point_coords=input_point, point_labels=input_label, multimask_output=False)result = Image.fromarray(image_rgb).convert("RGBA")result.putalpha(Image.fromarray((masks[0] * 255).astype(np.uint8)))result.save("photo_sam_prompt_bg.png")https://huggingface.co/briaai/RMBG-2.0https://huggingface.co/briaai/RMBG-1.4
BRIA AI 在 2024 年发布的 RMBG-2.0,在多个抠图基准上达到 SOTA。它是一个全能型背景移除模型,底层基于 BiRefNet 架构(见下一节),针对电商商品图、人像、动植物等数十个类别做了专门优化。与 rembg 1.x 相比,RMBG-2.0 在边缘精度和复杂背景场景下有显著提升。
部分版本可商用(需确认 License)。支持 HuggingFace 直接加载。
pip install torch torchvision pillow huggingface_hub transformersimport torchimport numpy as npfrom PIL import Imagefrom torchvision import transformsclassRMBG2:def__init__(self):from transformers import AutoModelForImageSegmentation self.model = AutoModelForImageSegmentation.from_pretrained("briaai/RMBG-2.0", trust_remote_code=True ) self.model.to("cuda"if torch.cuda.is_available() else"cpu") self.model.eval()defremove_bg(self, img_path, output_path): img = Image.open(img_path).convert("RGB") transform = transforms.Compose([ transforms.Resize((1024, 1024)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) input_tensor = transform(img).unsqueeze(0) input_tensor = input_tensor.to(self.model.device)with torch.no_grad(): preds = self.model(input_tensor)[-1].sigmoid().cpu() mask = preds.squeeze().numpy() mask = Image.fromarray((mask * 255).astype(np.uint8)) mask = mask.resize(img.size, Image.LANCZOS) img.putalpha(mask) img.save(output_path)rmbg2 = RMBG2()rmbg2.remove_bg("product.jpg", "product_no_bg.png")https://github.com/ZhengPeng7/BiRefNet
BiRefNet 是 RMBG-2.0 的底层架构,但它本身是一个更庞大的模型家族——提供 10 种不同变体,覆盖从极致精度到极致速度的全部需求。官方提供了多个专用微调版本:
BiRefNet | |
BiRefNet-portrait | |
BiRefNet-matting | |
BiRefNet-lite | |
BiRefNet-DIS |
BiRefNet 的核心创新是双边参考网络(Bilateral Reference Network)——将图像的局部细节和全局上下文分别编码后再融合,从而在细节保持和语义理解之间取得平衡。如果你需要为特定场景微调抠图模型,BiRefNet 是目前最灵活的基座。
pip install torch torchvision pillow opencv-python timmgit clone https://github.com/ZhengPeng7/BiRefNet.gitcd BiRefNetimport torchimport numpy as npfrom PIL import Imagefrom torchvision import transformsimport syssys.path.append("./BiRefNet")defbirefnet_remove_bg(img_path, output_path, model_type="general"):"""BiRefNet 通用背景移除 model_type: 'general' | 'portrait' | 'matting' | 'lite' """# 根据类型加载对应权重 ckpt_paths = {"general": "BiRefNet/ckpt/BiRefNet.pth","portrait": "BiRefNet/ckpt/BiRefNet-portrait.pth","matting": "BiRefNet/ckpt/BiRefNet-matting.pth", }from models.birefnet import BiRefNet model = BiRefNet(bb_pretrained=False) state_dict = torch.load(ckpt_paths[model_type], map_location="cpu") model.load_state_dict(state_dict, strict=True) model.eval() img = Image.open(img_path).convert("RGB") orig_size = img.size transform = transforms.Compose([ transforms.Resize((1024, 1024)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) input_tensor = transform(img).unsqueeze(0)with torch.no_grad(): pred = model(input_tensor)[-1].sigmoid().cpu() mask = pred.squeeze().numpy() mask = Image.fromarray((mask * 255).astype(np.uint8)) mask = mask.resize(orig_size, Image.LANCZOS) img.putalpha(mask) img.save(output_path)birefnet_remove_bg("photo.jpg", "photo_birefnet.png", model_type="portrait")https://github.com/plemeri/InSPyReNet
InSPyReNet 基于 Transformer 架构,最大的特点是模型小巧轻便——即使在 CPU 上也能运行,速度很快。它专为本地资源有限但追求高效率的场景设计,特别适合没有 GPU 的个人用户。
与大多数基于 CNN 的抠图模型不同,InSPyReNet 使用 Transformer 的自注意力机制来捕获全局上下文,这使它在处理复杂背景中的主体分离时有一定优势。在 ComfyUI 社区中有活跃的集成和使用。
pip install torch torchvision pillow opencv-pythongit clone https://github.com/plemeri/InSPyReNet.gitcd InSPyReNetpip install -r requirements.txtimport torchimport numpy as npfrom PIL import Imagefrom torchvision import transformsdefinspyrenet_remove_bg(img_path, output_path):"""InSPyReNet 背景移除 —— CPU 友好"""# 加载模型(可通过 torch.hub 或克隆仓库后本地加载)from inspyrenet import InSPyReNet_S model = InSPyReNet_S(pretrained=True) device = "cuda"if torch.cuda.is_available() else"cpu" model.to(device) model.eval() img = Image.open(img_path).convert("RGB") orig_size = img.size transform = transforms.Compose([ transforms.Resize((1024, 1024)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) input_tensor = transform(img).unsqueeze(0).to(device)with torch.no_grad(): pred = model(input_tensor)if isinstance(pred, (list, tuple)): pred = pred[-1] mask = pred.sigmoid().cpu().squeeze().numpy() mask = Image.fromarray((mask * 255).astype(np.uint8)) mask = mask.resize(orig_size, Image.LANCZOS) img.putalpha(mask) img.save(output_path)inspyrenet_remove_bg("photo.jpg", "photo_inspyrenet.png")https://github.com/PramaLLC/BEN2
BEN2(Background Erase Network v2)是一个优先保证前景主体完整的背景擦除模型。与其他模型追求"极致边缘精度"不同,BEN2 的设计理念是"宁可留一点背景,也不能切掉前景"——这对电商产品图至关重要:你不能把产品的边角给切没了。
BEN2 的另一大亮点是能处理 4K 超高清图像和视频,在同类模型中非常少见。如果你需要批量处理高清商品图或视频抠图,BEN2 是目前最合适的选择之一。
pip install torch torchvision pillow opencv-pythongit clone https://github.com/PramaLLC/BEN2.gitcd BEN2pip install -r requirements.txtimport torchimport numpy as npfrom PIL import Imagefrom torchvision import transformsdefben2_remove_bg(img_path, output_path):"""BEN2 背景移除 —— 优先保留前景完整性"""# 加载模型(具体加载方式参见官方仓库)# 此处给出调用框架,实际权重文件从 releases 下载from ben2 import BEN2Model model = BEN2Model.from_pretrained("ben2_weights.pth") device = "cuda"if torch.cuda.is_available() else"cpu" model.to(device) model.eval() img = Image.open(img_path).convert("RGB") orig_size = img.size# BEN2 支持高分辨率输入 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]) input_tensor = transform(img).unsqueeze(0).to(device)with torch.no_grad(): mask = model(input_tensor).sigmoid().cpu().squeeze().numpy() mask = Image.fromarray((mask * 255).astype(np.uint8)) mask = mask.resize(orig_size, Image.LANCZOS) img.putalpha(mask) img.save(output_path)ben2_remove_bg("product_4k.jpg", "product_4k_bg.png")https://github.com/PaddlePaddle/PaddleSeg https://openi.pcl.ac.cn/PaddlePaddle/PaddleSeg/modelart
PP-Matting 是百度飞桨(PaddlePaddle)生态下的高精度人像抠图模型,以出色的发丝级精细分割能力闻名。它在 PaddleSeg 框架下提供了多种场景和分辨率变体,覆盖从移动端到服务端的完整部署需求。
PP-Matting 的核心优势在于其基于 PaddlePaddle 的训练和推理优化——如果你已经在使用百度飞桨生态(如 PaddleOCR、PaddleDetection),PP-Matting 可以无缝集成。对中文开发者友好,文档和社区支持完善。
pip install paddlepaddle paddlesegimport paddlefrom paddleseg.models import PPMattingfrom paddleseg.utils import predictimport cv2from PIL import Imageimport numpy as npdefppmatting_remove_bg(img_path, output_path):"""PP-Matting 人像背景移除""" model = PPMatting(backbone="PP-Matting")# 加载预训练权重 model_path = "ppmatting_pretrained.pdparams" model.set_state_dict(paddle.load(model_path)) model.eval() img = cv2.imread(img_path) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_tensor = paddle.to_tensor(img_rgb.transpose(2, 0, 1)[None, ...].astype(np.float32))with paddle.no_grad(): alpha = model(img_tensor)[0].numpy()[0, 0]# 后处理 alpha = (alpha * 255).clip(0, 255).astype(np.uint8) result = Image.fromarray(img_rgb).convert("RGBA") result.putalpha(Image.fromarray(alpha)) result.save(output_path)ppmatting_remove_bg("portrait.jpg", "portrait_ppmatting.png")https://github.com/hyHy-1990/hy_bgmatting
Background Matting 是一种需要额外纯背景图辅助计算的高精度抠图模型。它的核心创新在于:如果你能提供一张没有人物的"纯背景"照片作为参考,模型就可以非常精确地将前景人物从当前帧中分离出来。
在 RGB-D 摄像头辅助下,可以做到 4K 分辨率 30fps 的实时抠像效果,多用于专业影视制作和虚拟演播室。虽然使用门槛比 trimap-free 模型高(需要背景图),但精度也更高。
git clone https://github.com/hyHy-1990/hy_bgmatting.gitcd hy_bgmattingpip install -r requirements.txtimport torchimport cv2import numpy as npfrom PIL import Imagedefbg_matting_remove(img_path, bg_path, output_path):"""Background Matting —— 需要参考背景图"""# 加载原图和背景参考图 img = cv2.imread(img_path) bg = cv2.imread(bg_path)# 转为 RGB img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) bg_rgb = cv2.cvtColor(bg, cv2.COLOR_BGR2RGB)# 模型推理(此处为框架性示例,实际需加载具体权重)# 核心思路:比较 img 和 bg 的差异 → 生成 alpha 遮罩 diff = cv2.absdiff(img_rgb.astype(np.float32), bg_rgb.astype(np.float32)) alpha_approx = np.clip(diff.mean(axis=2) / 50.0, 0, 1) # 简化版示意 result = Image.fromarray(img_rgb).convert("RGBA") result.putalpha(Image.fromarray((alpha_approx * 255).astype(np.uint8))) result.save(output_path)bg_matting_remove("person.jpg", "empty_room.jpg", "person_matted.png")https://github.com/MatteoKartoon/BiRefNet
ToonOut 是 BiRefNet 针对动漫和插画风格微调的专用模型。普通抠图模型处理动漫图像时常见的"涂抹头发丝""线条艺术断裂"和"半透明效果丢失"问题,ToonOut 都能完美处理。
它是二次元创作的首选——无论是提取角色立绘、处理漫画扫描件,还是为插画配透明背景,ToonOut 都能保持线条的锐利和色彩的准确。如果你用的是 Stable Diffusion / ComfyUI 工作流,ToonOut 作为抠图预处理步骤可以大幅提升后续效果。
# ToonOut 是 BiRefNet 的衍生,安装方式类似git clone https://github.com/MatteoKartoon/BiRefNet.gitcd BiRefNetpip install -r requirements.txt# ToonOut 的调用方式与 BiRefNet 相同,区别在于权重文件# 参见第五节 BiRefNet 代码,将 model_type 替换为 "toonout"deftoonout_remove_bg(img_path, output_path):"""ToonOut 动漫图像背景移除"""# 方式一:直接使用 ComfyUI 的 Inspyrenet-Rembg 节点# 方式二:通过 BiRefNet 框架加载 ToonOut 权重from models.birefnet import BiRefNet model = BiRefNet(bb_pretrained=False)# 加载 ToonOut 专用权重 ckpt = torch.load("toonout_weights.pth", map_location="cpu") model.load_state_dict(ckpt, strict=True) model.eval()# 预处理和推理流程与 BiRefNet 相同(见第五节)# ...toonout_remove_bg("anime_art.png", "anime_art_transparent.png")https://github.com/tensorflow/models/tree/master/research/deeplab
DeepLabV3+ 是谷歌开源的经典语义分割模型,在计算机视觉领域有深远影响。它本身不是专门的抠图模型,而是作为底层的语义分割技术被大量集成在其他模型中。通过 atrous spatial pyramid pooling(ASPP)和解码器结构,DeepLabV3+ 能捕获多尺度的上下文信息。
虽然现在有更新的模型超越了它,但 DeepLabV3+ 仍然是微调自定义抠图任务的一个可靠基座——特别是当你需要用较小的数据集做迁移学习时。
https://github.com/xuebinqin/DIS
DIS(二分图像分割)是中科院发布的高精度分割模型,在 DIS5K 数据集上训练,专门针对"物体从背景中分离"这个二分问题做了架构优化。与 U²-Net 相比,DIS 在精细边缘(如毛发、蕾丝、半透明物体)上表现更好。
pip install torch torchvision pillow opencv-pythonimport torchimport numpy as npfrom PIL import Imagefrom torchvision import transformsmodel = torch.hub.load("xuebinqin/U-2-Net", "u2net", pretrained=True)model.eval()defdis_remove_bg(img_path, output_path): img = Image.open(img_path).convert("RGB") orig_size = img.size transform = transforms.Compose([ transforms.Resize((320, 320)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) input_tensor = transform(img).unsqueeze(0)with torch.no_grad(): mask = model(input_tensor)[0][0, 0].numpy() mask = (mask - mask.min()) / (mask.max() - mask.min()) mask_img = Image.fromarray((mask * 255).astype(np.uint8)) mask_img = mask_img.resize(orig_size, Image.LANCZOS) img.putalpha(mask_img) img.save(output_path)dis_remove_bg("fine_detail.jpg", "fine_detail_bg.png")先看你有什么硬件,再选你能跑什么模型,最后看场景匹配。
| 高端 GPU ≥8GB | ||
| 中端 GPU 4-8GB | ||
| 入门 GPU 2-4GB | ||
| 无 GPU(强 CPU) | ||
| 无 GPU(普通电脑) | ||
| 无 GPU(低配笔记本) | ||
| 移动端 / Web | ||
| MacBook M1/M2/M3 |
| rembg | ||
| MODNet | ||
| BRIA RMBG-2.0 | ||
| SAM | ||
| Background Matting | ||
| ToonOut | ||
| InSPyReNet | ||
| BEN2 | ||
| BiRefNet |
| PaddlePaddle 生态 | PP-Matting |
"""批量抠图脚本 —— 一个文件夹全部搞定"""import osfrom pathlib import Pathfrom rembg import removefrom PIL import ImageINPUT_DIR = "./input_photos"OUTPUT_DIR = "./output_photos"Path(OUTPUT_DIR).mkdir(exist_ok=True)for filename in os.listdir(INPUT_DIR):if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')): input_path = os.path.join(INPUT_DIR, filename) output_path = os.path.join(OUTPUT_DIR, f"{Path(filename).stem}.png") img = Image.open(input_path) result = remove(img) result.save(output_path) print(f"✅ {filename} → {output_path}")print(f"\n全部完成!处理了 {len(os.listdir(OUTPUT_DIR))} 张图片。")