Image Segmentation
Transformers
Safetensors
birefnet_v2
background-removal
mask-generation
Dichotomous Image Segmentation
Camouflaged Object Detection
Salient Object Detection
custom_code
Eval Results (legacy)
Run this model with HF Jobs
Run ZhengPeng7/BiRefNet-V2-COD on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ZhengPeng7/BiRefNet-V2-COD. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ZhengPeng7/BiRefNet-V2-COD on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ZhengPeng7/BiRefNet-V2-COD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ZhengPeng7/BiRefNet-V2-COD with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-segmentation", model="ZhengPeng7/BiRefNet-V2-COD", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForImageSegmentation model = AutoModelForImageSegmentation.from_pretrained("ZhengPeng7/BiRefNet-V2-COD", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download handler.py from ZhengPeng7/BiRefNet-V2-COD: direct link, hf CLI and curl.
- Browser
- Download file 4.05 kB
-
https://huggingface.co/ZhengPeng7/BiRefNet-V2-COD/resolve/main/handler.py
- Command line
-
hf download hf://ZhengPeng7/BiRefNet-V2-COD/handler.py
-
curl -L -o handler.py https://huggingface.co/ZhengPeng7/BiRefNet-V2-COD/resolve/main/handler.py
4.05 kB
| # Custom handler for Hugging Face Inference Endpoints, adapted from the BiRefNet (v1) handler, which refers to | |
| # https://huggingface.co/not-lain/BiRefNet/raw/main/handler.py. | |
| from typing import Dict, Any, Tuple | |
| import os | |
| import requests | |
| from io import BytesIO | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| import torch | |
| from torchvision import transforms | |
| from transformers import AutoModelForImageSegmentation | |
| torch.set_float32_matmul_precision(["high", "highest"][0]) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| ### image_proc.py | |
| def refine_foreground(image, mask, r=90): | |
| if mask.size != image.size: | |
| mask = mask.resize(image.size) | |
| image = np.array(image) / 255.0 | |
| mask = np.array(mask) / 255.0 | |
| estimated_foreground = FB_blur_fusion_foreground_estimator_2(image, mask, r=r) | |
| image_masked = Image.fromarray((estimated_foreground * 255.0).astype(np.uint8)) | |
| return image_masked | |
| def FB_blur_fusion_foreground_estimator_2(image, alpha, r=90): | |
| # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation | |
| alpha = alpha[:, :, None] | |
| F, blur_B = FB_blur_fusion_foreground_estimator(image, image, image, alpha, r) | |
| return FB_blur_fusion_foreground_estimator(image, F, blur_B, alpha, r=6)[0] | |
| def FB_blur_fusion_foreground_estimator(image, F, B, alpha, r=90): | |
| if isinstance(image, Image.Image): | |
| image = np.array(image) / 255.0 | |
| blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None] | |
| blurred_FA = cv2.blur(F * alpha, (r, r)) | |
| blurred_F = blurred_FA / (blurred_alpha + 1e-5) | |
| blurred_B1A = cv2.blur(B * (1 - alpha), (r, r)) | |
| blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5) | |
| F = blurred_F + alpha * \ | |
| (image - alpha * blurred_F - (1 - alpha) * blurred_B) | |
| F = np.clip(F, 0, 1) | |
| return F, blurred_B | |
| class ImagePreprocessor(): | |
| def __init__(self, resolution: Tuple[int, int] = (1024, 1024)) -> None: | |
| self.transform_image = transforms.Compose([ | |
| transforms.Resize(resolution), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), | |
| ]) | |
| def proc(self, image: Image.Image) -> torch.Tensor: | |
| image = self.transform_image(image) | |
| return image | |
| class EndpointHandler(): | |
| def __init__(self, path=''): | |
| # path = the local copy of this model repository. | |
| self.birefnet = AutoModelForImageSegmentation.from_pretrained(path, trust_remote_code=True) | |
| self.birefnet.to(device) | |
| self.birefnet.eval() | |
| # config.size is (W, H); Resize takes (H, W). | |
| self.resolution = tuple(self.birefnet.config.size[::-1]) | |
| def __call__(self, data: Dict[str, Any]): | |
| """ | |
| data args: | |
| inputs (:obj: `str` | `np.ndarray`): image path, image URL or RGB image array | |
| Return: | |
| A :obj:`PIL.Image.Image`: the RGBA image whose alpha channel is the predicted mask | |
| """ | |
| image_src = data["inputs"] | |
| if isinstance(image_src, str): | |
| if os.path.isfile(image_src): | |
| image_ori = Image.open(image_src) | |
| else: | |
| response = requests.get(image_src) | |
| image_data = BytesIO(response.content) | |
| image_ori = Image.open(image_data) | |
| else: | |
| image_ori = Image.fromarray(image_src) | |
| image = image_ori.convert('RGB') | |
| # Preprocess the image | |
| image_preprocessor = ImagePreprocessor(resolution=self.resolution) | |
| image_proc = image_preprocessor.proc(image) | |
| image_proc = image_proc.unsqueeze(0) | |
| # Prediction: the model runs under bf16 autocast by itself on GPU. | |
| with torch.no_grad(): | |
| preds = self.birefnet(image_proc.to(device))[-1].sigmoid().cpu() | |
| pred = preds[0].squeeze() | |
| # Show Results | |
| pred_pil = transforms.ToPILImage()(pred) | |
| image_masked = refine_foreground(image, pred_pil) | |
| image_masked.putalpha(pred_pil.resize(image.size)) | |
| return image_masked | |