File size: 822 Bytes
8c10814
e612aac
8c10814
 
 
 
e612aac
8c10814
e612aac
8c10814
 
e612aac
8c10814
e612aac
 
8c10814
 
 
 
e612aac
 
8c10814
 
 
 
e612aac
8c10814
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""Background removal with the commercially permissive BiRefNet model.

The model is provided by ``rembg`` and is downloaded once on first use. See
README.md for model attribution and hosting notes.
"""
# pylint: disable=broad-exception-caught

from functools import lru_cache

from PIL import Image
from rembg import new_session, remove

MODEL_NAME = "birefnet-general"


@lru_cache(maxsize=1)
def get_session():
    """Create and retain one BiRefNet inference session per process."""
    return new_session(MODEL_NAME)


def remove_background(image: Image.Image) -> Image.Image:
    """Return *image* as an RGBA image with its background made transparent."""
    if image is None:
        raise ValueError("Please upload an image first.")

    return remove(image.convert("RGBA"), session=get_session()).convert("RGBA")