vncgabriel commited on
Commit
96a5052
·
verified ·
1 Parent(s): aa1d816

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -31
app.py CHANGED
@@ -1,40 +1,34 @@
1
- # app.py
2
  import gradio as gr
 
3
  import torch
4
- from huggingface_hub import hf_hub_download
5
  from inference import load_model, predict
6
- from PIL import Image
7
- import numpy as np
8
-
9
- # Baixa o peso .bin do Model Hub
10
- model_path = hf_hub_download(
11
- repo_id="vncgabriel/instancia-segmentation-model",
12
- filename="pytorch_model.bin",
13
- repo_type="model",
14
- )
15
 
16
- # Carrega o modelo
17
- device = "cuda" if torch.cuda.is_available() else "cpu"
18
- model = load_model(model_path, device=device)
19
 
20
- def segment(image: Image.Image):
21
- img_arr = np.array(image).astype(np.float32) / 255.0
22
- img_tensor = torch.from_numpy(img_arr).permute(2, 0, 1).to(device)
23
- mask = predict(model, img_tensor).cpu().numpy()
24
- bin_mask = (mask > 0.5).astype(np.uint8) * 255
25
- overlay = image.convert("RGBA")
26
- mask_img = Image.fromarray(bin_mask).convert("L")
27
- red = Image.new("RGBA", image.size, color=(255, 0, 0, 100))
28
- overlay.paste(red, mask=mask_img)
29
- return overlay
 
 
30
 
31
- iface = gr.Interface(
32
- fn=segment,
33
- inputs=gr.Image(type="pil"),
34
- outputs=gr.Image(type="pil"),
35
- title="Segmentação de Instâncias",
36
- description="Envie uma imagem e obtenha a segmentação de instâncias usando UNet pré-treinado."
 
 
37
  )
38
 
39
  if __name__ == "__main__":
40
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
1
  import gradio as gr
2
+ import numpy as np
3
  import torch
 
4
  from inference import load_model, predict
 
 
 
 
 
 
 
 
 
5
 
6
+ # Carrega o modelo na inicialização (GPU se disponível)
7
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
8
+ model = load_model("pytorch_model.bin", device)
9
 
10
+ def segment_instance(image):
11
+ # Converte imagem PIL em tensor normalizado [C,H,W]
12
+ image_array = np.array(image).astype(np.float32) / 255.0
13
+ image_tensor = torch.from_numpy(image_array).permute(2, 0, 1)
14
+ # Obtém máscara predita [1,H,W]
15
+ mask_tensor = predict(model, image_tensor.to(device))
16
+ mask = mask_tensor.squeeze(0).cpu().numpy()
17
+ # Limiares binários e escala para 0-255
18
+ mask = (mask > 0.5).astype(np.uint8) * 255
19
+ # Converte para 3 canais para exibição
20
+ mask_image = np.stack([mask]*3, axis=-1)
21
+ return mask_image
22
 
23
+ title = "Segmentação de Instâncias"
24
+ description = "Envie uma imagem e obtenha a segmentação de instâncias usando UNet pré-treinado."
25
+ demo = gr.Interface(
26
+ fn=segment_instance,
27
+ inputs=gr.Image(type="pil", label="Entrada"),
28
+ outputs=gr.Image(type="numpy", label="Máscara"),
29
+ title=title,
30
+ description=description
31
  )
32
 
33
  if __name__ == "__main__":
34
+ demo.launch()