0notexist0 commited on
Commit
4b267d2
·
verified ·
1 Parent(s): 57c0197

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -13
app.py CHANGED
@@ -1,18 +1,28 @@
1
- from transformers import AutoProcessor, AutoModelForImageSegmentation
 
2
  from PIL import Image
3
- import torch
4
 
5
- # Carica modello e processor
6
- processor = AutoProcessor.from_pretrained("BritishWerewolf/U-2-Netp")
7
- model = AutoModelForImageSegmentation.from_pretrained("BritishWerewolf/U-2-Netp")
8
 
9
- # Prepara l’immagine
10
- img = Image.open("input.jpg").convert("RGB")
11
- inputs = processor(images=img, return_tensors="pt")
 
12
 
13
- # Inferenzia maschera
14
- with torch.no_grad():
15
- outputs = model(**inputs)
16
- mask = outputs.logits.argmax(dim=1)[0].cpu().numpy()
 
17
 
18
- # Applica maschera allimmagine originale...
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
  from PIL import Image
4
+ import numpy as np
5
 
6
+ # 1) Carica il modello di segmentazione
7
+ seg = pipeline("image-segmentation", model="BritishWerewolf/U-2-Netp", framework="pt")
 
8
 
9
+ def remove_bg(image: Image.Image):
10
+ # 2) Ottieni la maschera
11
+ outputs = seg(image)
12
+ mask = outputs[0]["mask"].astype(np.uint8) * 255
13
 
14
+ # 3) Applica la maschera all’alpha channel
15
+ rgba = image.convert("RGBA")
16
+ rgba_arr = np.array(rgba)
17
+ rgba_arr[..., 3] = mask # canale alpha = mask
18
+ return Image.fromarray(rgba_arr)
19
 
20
+ # 4) Definisci linterfaccia “chat”
21
+ with gr.Blocks() as demo:
22
+ chatbot = gr.Chatbot(label="BG-Removal Bot")
23
+ img_in = gr.Image(type="pil", label="Invia la tua foto")
24
+ img_out = gr.Image(type="pil", label="Risultato")
25
+
26
+ img_in.change(fn=remove_bg, inputs=img_in, outputs=img_out)
27
+
28
+ demo.launch()