模型简介
模型特点
模型能力
使用案例
🚀 BiRefNet
BiRefNet是用于高分辨率二分图像分割的模型,可应用于背景去除、掩码生成等多个领域,在多个相关任务中取得了SOTA性能。
🚀 快速开始
0. 安装依赖包
pip install -qr https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/requirements.txt
1. 加载BiRefNet
使用HuggingFace的代码和权重
仅使用HuggingFace上的权重,优点是无需手动下载BiRefNet代码;缺点是HuggingFace上的代码可能不是最新版本(我会尽量保持其为最新版本)。
# 加载带有权重的BiRefNet
from transformers import AutoModelForImageSegmentation
birefnet = AutoModelForImageSegmentation.from_pretrained('ZhengPeng7/BiRefNet_HR', trust_remote_code=True)
使用GitHub的代码和HuggingFace的权重
仅使用HuggingFace上的权重,优点是代码始终是最新的;缺点是需要从我的GitHub克隆BiRefNet仓库。
# 下载代码
git clone https://github.com/ZhengPeng7/BiRefNet.git
cd BiRefNet
# 本地使用代码
from models.birefnet import BiRefNet
# 从Hugging Face Models加载权重
birefnet = BiRefNet.from_pretrained('ZhengPeng7/BiRefNet_HR')
使用GitHub的代码和本地的权重
本地同时使用代码和权重。
# 本地使用代码和权重
import torch
from utils import check_state_dict
birefnet = BiRefNet(bb_pretrained=False)
state_dict = torch.load(PATH_TO_WEIGHT, map_location='cpu')
state_dict = check_state_dict(state_dict)
birefnet.load_state_dict(state_dict)
使用加载好的BiRefNet进行推理
# 导入库
from PIL import Image
import matplotlib.pyplot as plt
import torch
from torchvision import transforms
from models.birefnet import BiRefNet
birefnet = ... # -- 应使用上述代码加载BiRefNet,任意一种方式均可
torch.set_float32_matmul_precision(['high', 'highest'][0])
birefnet.to('cuda')
birefnet.eval()
birefnet.half()
def extract_object(birefnet, imagepath):
# 数据设置
image_size = (2048, 2048)
transform_image = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
image = Image.open(imagepath)
input_images = transform_image(image).unsqueeze(0).to('cuda').half()
# 预测
with torch.no_grad():
preds = birefnet(input_images)[-1].sigmoid().cpu()
pred = preds[0].squeeze()
pred_pil = transforms.ToPILImage()(pred)
mask = pred_pil.resize(image.size)
image.putalpha(mask)
return image, mask
# 可视化
plt.axis("off")
plt.imshow(extract_object(birefnet, imagepath='PATH-TO-YOUR_IMAGE.jpg')[0])
plt.show()
2. 本地使用推理端点
你可能需要自己点击deploy并设置端点,这会产生一些费用。
import requests
import base64
from io import BytesIO
from PIL import Image
YOUR_HF_TOKEN = 'xxx'
API_URL = "xxx"
headers = {
"Authorization": "Bearer {}".format(YOUR_HF_TOKEN)
}
def base64_to_bytes(base64_string):
# 如果存在数据URI前缀,则移除
if "data:image" in base64_string:
base64_string = base64_string.split(",")[1]
# 将Base64字符串解码为字节
image_bytes = base64.b64decode(base64_string)
return image_bytes
def bytes_to_base64(image_bytes):
# 创建一个BytesIO对象来处理图像数据
image_stream = BytesIO(image_bytes)
# 使用Pillow (PIL)打开图像
image = Image.open(image_stream)
return image
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
output = query({
"inputs": "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg",
"parameters": {}
})
output_image = bytes_to_base64(base64_to_bytes(output))
output_image
✨ 主要特性
- 多任务适用性:可用于背景去除、掩码生成、二分图像分割、伪装目标检测、显著目标检测等多个任务。
- 高分辨率推理:该模型使用
2048x2048
的图像进行训练,以实现更高分辨率的推理。 - SOTA性能:在三个任务(DIS、HRSOD和COD)上取得了SOTA性能。
📦 安装指南
pip install -qr https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/requirements.txt
💻 使用示例
基础用法
# 加载带有权重的BiRefNet
from transformers import AutoModelForImageSegmentation
birefnet = AutoModelForImageSegmentation.from_pretrained('ZhengPeng7/BiRefNet_HR', trust_remote_code=True)
高级用法
# 本地使用代码和权重
import torch
from utils import check_state_dict
birefnet = BiRefNet(bb_pretrained=False)
state_dict = torch.load(PATH_TO_WEIGHT, map_location='cpu')
state_dict = check_state_dict(state_dict)
birefnet.load_state_dict(state_dict)
📚 详细文档
模型性能
所有测试均在FP16模式下进行。 | 数据集 | 方法 | 分辨率 | maxFm | wFmeasure | MAE | Smeasure | meanEm | HCE | maxEm | meanFm | adpEm | adpFm | mBA | maxBIoU | meanBIoU | | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | | DIS-VD | BiRefNet_HR-general-epoch_130 | 2048x2048 | .925 | .894 | .026 | .927 | .952 | 811 | .960 | .909 | .944 | .888 | .828 | .837 | .817 | | DIS-VD | BiRefNet_HR-general-epoch_130 | 1024x1024 | .876 | .840 | .041 | .893 | .913 | 1348 | .926 | .860 | .930 | .857 | .765 | .769 | .742 | | DIS-VD | BiRefNet-general-epoch_244 | 2048x2048 | .888 | .858 | .037 | .898 | .934 | 811 | .941 | .878 | .927 | .862 | .802 | .790 | .776 | | DIS-VD | BiRefNet-general-epoch_244 | 1024x1024 | .908 | .877 | .034 | .912 | .943 | 1128 | .953 | .894 | .944 | .881 | .796 | .812 | .789 |
模型训练和验证
这个用于标准二分图像分割(DIS)的BiRefNet在DIS-TR上进行训练,并在DIS-TEs和DIS-VD上进行验证。
论文信息
本文提出的BiRefNet的权重包含在本仓库中,该论文为 "Bilateral Reference for High-Resolution Dichotomous Image Segmentation" (CAAI AIR 2024)。
作者信息
相关链接
示例图片
DIS-Sample_1 | DIS-Sample_2 |
---|---|
在线演示
🔧 技术细节
本仓库包含了论文中提出的BiRefNet的权重,该模型在三个任务(DIS、HRSOD和COD)上取得了SOTA性能。模型使用2048x2048
的图像进行训练,以实现更高分辨率的推理。
📄 许可证
本项目采用MIT许可证。
致谢
非常感谢@freepik为训练此模型提供的GPU资源支持!
引用
@article{zheng2024birefnet,
title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation},
author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu},
journal={CAAI Artificial Intelligence Research},
volume = {3},
pages = {9150038},
year={2024}
}











