feat: upgrade to BiRefNet SOTA background removal model

- Switch default model from U2-Net to BiRefNet (state-of-the-art)
- Add 6 model options: BiRefNet, BiRefNet Lite, BiRefNet Portrait,
  BRIA RMBG, IS-Net, U2-Net
- Add animated progress bar with stage indicators (loading model,
  analyzing, removing, refining edges) and elapsed timer
- Add intuitive background color presets (Transparent, White, Black,
  Red, Green, Blue) as clickable buttons + custom color picker
- Handle background color compositing in Python (PIL alpha composite)
- Add checkerboard pattern to before/after slider for transparency
- Pre-bake BiRefNet model (973MB) in Docker image for instant use
This commit is contained in:
Siddharth Kumar Sah
2026-03-22 19:51:35 +08:00
parent 22b08c0475
commit 77ee8469d8
3 changed files with 140 additions and 42 deletions
+29 -6
View File
@@ -1,4 +1,4 @@
"""Background removal using rembg."""
"""Background removal using rembg with state-of-the-art BiRefNet models."""
import sys
import json
@@ -8,25 +8,48 @@ def main():
output_path = sys.argv[2]
settings = json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
model = settings.get("model", "u2net")
model = settings.get("model", "birefnet-general")
bg_color = settings.get("backgroundColor", "")
try:
from rembg import remove
from rembg import remove, new_session
from PIL import Image
import io
print(json.dumps({"progress": "loading_model"}), flush=True)
# Create a session with the selected model
session = new_session(model)
with open(input_path, "rb") as f:
input_data = f.read()
# Try with alpha matting first for better edges, but fall back
# without it if the image triggers the known rembg matting error
print(json.dumps({"progress": "processing"}), flush=True)
# Try with alpha matting first for better edges
try:
output_data = remove(
input_data,
session=session,
alpha_matting=True,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10,
)
except Exception:
output_data = remove(input_data)
output_data = remove(input_data, session=session)
# If a background color is specified, composite onto it
if bg_color and bg_color.startswith("#"):
img = Image.open(io.BytesIO(output_data)).convert("RGBA")
hex_color = bg_color.lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
bg = Image.new("RGBA", img.size, (r, g, b, 255))
bg.paste(img, mask=img.split()[3])
buf = io.BytesIO()
bg.save(buf, format="PNG")
output_data = buf.getvalue()
with open(output_path, "wb") as f:
f.write(output_data)