Muhammad8815 commited on
Commit
8ac35d9
·
verified ·
1 Parent(s): 596566c

Upload 17 files

Browse files
Files changed (3) hide show
  1. README.md +58 -41
  2. app.py +67 -0
  3. briarmbg.py +1 -1
README.md CHANGED
@@ -1,41 +1,58 @@
1
- ---
2
- license: other
3
- license_name: custom-non-commercial
4
- license_link: https://huggingface.co/Muhammad8815/inno-rmbg-removal-8815/blob/main/LICENSE
5
- pipeline_tag: image-segmentation
6
- tags:
7
- - remove-background
8
- - background-removal
9
- - pytorch
10
- - onnx
11
- - image-segmentation
12
- ---
13
-
14
- # Inno RMBG Removal v1.0
15
-
16
- This is a custom-trained image background removal model using PyTorch and ONNX. It performs pixel-wise background removal on input images with high accuracy.
17
-
18
- ## Model Highlights
19
-
20
- - Supports PyTorch `.pth` and ONNX inference.
21
- - Trained on diverse images of objects, people, and scenes.
22
- - Provides a binary mask of the foreground, suitable for downstream tasks (e.g. background replacement, transparency effects).
23
-
24
- ## Example Input/Output
25
-
26
- **Input:**
27
- ![example input](example_input.jpg)
28
-
29
- **Output (no background):**
30
- ![result](results.png)
31
-
32
- ## Inference Code (PyTorch)
33
- ```python
34
- from PIL import Image
35
- from utilities import preprocess_image, postprocess_image, load_model
36
-
37
- model = load_model("model.pth")
38
- image = Image.open("example_input.jpg")
39
- mask = model.predict(image)
40
- image.putalpha(mask)
41
- image.save("output.png")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Inno Background Remover
3
+ emoji: 🪄
4
+ colorFrom: pink
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: "4.19.2"
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # 🪄 Inno RMBG Removal v1.0
13
+
14
+ This Space runs a custom-trained image background removal model using PyTorch and ONNX.
15
+ It performs pixel-wise background removal on input images with high accuracy using a Gradio interface.
16
+
17
+ ---
18
+
19
+ ## ✨ Model Highlights
20
+
21
+ - Trained on diverse images of objects, people, and scenes.
22
+ - Outputs a binary mask of the foreground.
23
+ - Works with `.pth` and ONNX formats.
24
+ - Useful for background replacement or transparent cutouts.
25
+
26
+ ---
27
+
28
+ ## 📦 Input / Output
29
+
30
+ **Input Image:**
31
+
32
+ ![example input](example_input.jpg)
33
+
34
+ **Output (no background):**
35
+
36
+ ![result](results.png)
37
+
38
+ ---
39
+
40
+ ## 🧪 How It Works
41
+
42
+ 1. Upload an image using the UI.
43
+ 2. The model generates a mask for the foreground.
44
+ 3. The output is a transparent PNG or white background version.
45
+
46
+ ---
47
+
48
+ ## ⚙️ Inference Code (example)
49
+
50
+ ```python
51
+ from PIL import Image
52
+ from utilities import preprocess_image, postprocess_image, load_model
53
+
54
+ model = load_model("model.pth")
55
+ image = Image.open("example_input.jpg")
56
+ mask = model.predict(image)
57
+ image.putalpha(mask)
58
+ image.save("output.png")
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from briarmbg import BriaRMBG
3
+ from PIL import Image
4
+ import torch
5
+ import torchvision.transforms as T
6
+ import os
7
+ import json
8
+ from fastapi import Request, HTTPException
9
+
10
+ # ===== Load API key from Hugging Face secret or fallback =====
11
+ API_KEY = os.getenv("API_KEY", "sk_muhammad8815_Z4gXr93nPqT2LwV8")
12
+
13
+ # ===== Load model =====
14
+ model = BriaRMBG.from_pretrained("./")
15
+ model.load_state_dict(torch.load("model.pth", map_location="cpu"))
16
+ model.eval()
17
+
18
+ # ===== Define preprocessing =====
19
+ transform = T.Compose([
20
+ T.Resize((512, 512)),
21
+ T.ToTensor()
22
+ ])
23
+
24
+ # ===== Background removal function with API key check =====
25
+ def remove_background(image, request: Request = None):
26
+ # Check for API key in Authorization header
27
+ if request is not None:
28
+ auth = request.headers.get("authorization")
29
+ if not auth or not auth.startswith("Bearer ") or auth.split(" ")[1] != API_KEY:
30
+ raise HTTPException(status_code=401, detail="Invalid or missing API key")
31
+
32
+ # Preprocess image
33
+ img = transform(image).unsqueeze(0)
34
+
35
+ with torch.no_grad():
36
+ result = model(img)
37
+
38
+ # Handle different result formats
39
+ if isinstance(result, dict) and "pred" in result:
40
+ result = result["pred"]
41
+ elif isinstance(result, (tuple, list)):
42
+ result = result[0]
43
+ if isinstance(result, list):
44
+ result = result[0]
45
+
46
+ result = result.squeeze().numpy()
47
+
48
+ # Apply transparency mask
49
+ image = image.resize((result.shape[1], result.shape[0]))
50
+ image = image.convert("RGBA")
51
+ pixels = image.load()
52
+
53
+ for y in range(image.height):
54
+ for x in range(image.width):
55
+ if result[y][x] < 0.5:
56
+ pixels[x, y] = (255, 255, 255, 0)
57
+
58
+ return image
59
+
60
+ # ===== Launch Gradio app with secure FastAPI request passthrough =====
61
+ gr.Interface(
62
+ fn=remove_background,
63
+ inputs=gr.Image(type="pil"),
64
+ outputs=gr.Image(type="pil"),
65
+ title="Background Remover",
66
+ allow_flagging="never"
67
+ ).launch()
briarmbg.py CHANGED
@@ -2,7 +2,7 @@ import torch
2
  import torch.nn as nn
3
  import torch.nn.functional as F
4
  from transformers import PreTrainedModel
5
- from .MyConfig import RMBGConfig
6
 
7
  class REBNCONV(nn.Module):
8
  def __init__(self,in_ch=3,out_ch=3,dirate=1,stride=1):
 
2
  import torch.nn as nn
3
  import torch.nn.functional as F
4
  from transformers import PreTrainedModel
5
+ from MyConfig import RMBGConfig
6
 
7
  class REBNCONV(nn.Module):
8
  def __init__(self,in_ch=3,out_ch=3,dirate=1,stride=1):