| DIS-Sample_1 | DIS-Sample_2 |
|---|---|
本仓库是论文“面向高分辨率二值图像分割的双侧参考”的官方实现(CAAI AIR 2024)。
访问我们的 GitHub 仓库:https://github.com/ZhengPeng7/BiRefNet 以获取更多详情——代码、文档和模型库!
pip install -qr https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/requirements.txt仅使用 HuggingFace 上的权重 —— 优点:无需手动下载 BiRefNet 代码;缺点:HuggingFace 上的代码可能不是最新版本(我会尽量保持其始终为最新版本)。
# Load BiRefNet with weights
from transformers import AutoModelForImageSegmentation
birefnet = AutoModelForImageSegmentation.from_pretrained('zhengpeng7/BiRefNet_lite', trust_remote_code=True)仅使用 HuggingFace 上的权重——优点:代码始终为最新版本;缺点:需要从我的 GitHub 克隆 BiRefNet 仓库。
# Download codes
git clone https://github.com/ZhengPeng7/BiRefNet.git
cd BiRefNet# Use codes locally
from models.birefnet import BiRefNet
# Load weights from Hugging Face Models
### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###
birefnet = BiRefNet.from_pretrained('zhengpeng7/BiRefNet_lite')仅使用本地权重和本地代码。
# Use codes and weights locally
### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###
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)# Imports
from PIL import Image
import matplotlib.pyplot as plt
import torch
from torchvision import transforms
from models.birefnet import BiRefNet
birefnet = ... # -- BiRefNet should be loaded with codes above, either way.
torch.set_float32_matmul_precision(['high', 'highest'][0])
birefnet.to('cuda')
birefnet.eval()
birefnet.half()
def extract_object(birefnet, imagepath):
# Data settings
image_size = (1024, 1024)
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()
# Prediction
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
# Visualization
plt.axis("off")
plt.imshow(extract_object(birefnet, imagepath='PATH-TO-YOUR_IMAGE.jpg')[0])
plt.show()
本 BiRefNet 面向标准二值图像分割(DIS),在 DIS-TR 上训练,并在 DIS-TEs 和 DIS-VD 上进行验证。
本仓库包含我们论文中提出的 BiRefNet 的权重,该模型在三项任务(DIS、HRSOD 和 COD)上取得了 SOTA 性能。
前往我的 GitHub 页面查看 BiRefNet 代码及最新更新:https://github.com/ZhengPeng7/BiRefNet :)
@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}
}