1 Nankai University 2 Northwestern Polytechnical University 3 National University of Defense Technology 4 Aalto University 5 Shanghai AI Laboratory 6 University of Trento
Only use the weights on HuggingFace -- Pro: No need to download BiRefNet codes manually; Con: Codes on HuggingFace might not be latest version (I'll try to keep them always latest).
1# Use codes locally2from models.birefnet import BiRefNet
34# Load weights from Hugging Face Models5### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###6birefnet = BiRefNet.from_pretrained('zhengpeng7/BiRefNet_lite')
Use codes from GitHub + weights from local space
Only use the weights and codes both locally.
python
1# Use codes and weights locally2### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###3import torch
4from utils import check_state_dict
56birefnet = BiRefNet(bb_pretrained=False)7state_dict = torch.load(PATH_TO_WEIGHT, map_location='cpu')8state_dict = check_state_dict(state_dict)9birefnet.load_state_dict(state_dict)
Use the loaded BiRefNet for inference
python
1# Imports2from PIL import Image
3import matplotlib.pyplot as plt
4import torch
5from torchvision import transforms
6from models.birefnet import BiRefNet
78birefnet =...# -- BiRefNet should be loaded with codes above, either way.9torch.set_float32_matmul_precision(['high','highest'][0])10birefnet.to('cuda')11birefnet.eval()12birefnet.half()1314defextract_object(birefnet, imagepath):15# Data settings16 image_size =(1024,1024)17 transform_image = transforms.Compose([18 transforms.Resize(image_size),19 transforms.ToTensor(),20 transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])21])2223 image = Image.open(imagepath)24 input_images = transform_image(image).unsqueeze(0).to('cuda').half()2526# Prediction27with torch.no_grad():28 preds = birefnet(input_images)[-1].sigmoid().cpu()29 pred = preds[0].squeeze()30 pred_pil = transforms.ToPILImage()(pred)31 mask = pred_pil.resize(image.size)32 image.putalpha(mask)33return image, mask
3435# Visualization36plt.axis("off")37plt.imshow(extract_object(birefnet, imagepath='PATH-TO-YOUR_IMAGE.jpg')[0])38plt.show()39
This BiRefNet for standard dichotomous image segmentation (DIS) is trained on DIS-TR and validated on DIS-TEs and DIS-VD.
Many thanks to @fal for their generous support on GPU resources for training better BiRefNet models.
Many thanks to @not-lain for his help on the better deployment of our BiRefNet model on HuggingFace.
Citation
@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}
}