Spaces:
Running on Zero
Running on Zero
Create segmentation.py
#2
by ViniciusFlausinoSilva - opened
- segmentation.py +57 -0
segmentation.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from rembg import remove, new_session
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Mantém a sessão carregada para não baixar/carregar
|
| 8 |
+
# o modelo novamente a cada imagem.
|
| 9 |
+
_session = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def carregar_segmentador():
|
| 13 |
+
global _session
|
| 14 |
+
|
| 15 |
+
if _session is None:
|
| 16 |
+
_session = new_session("isnet-general-use")
|
| 17 |
+
|
| 18 |
+
return _session
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def gerar_mascara(imagem: Image.Image):
|
| 22 |
+
"""
|
| 23 |
+
Gera uma máscara do objeto principal da imagem.
|
| 24 |
+
|
| 25 |
+
Branco = objeto
|
| 26 |
+
Preto = fundo
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
if imagem is None:
|
| 30 |
+
raise ValueError("Nenhuma imagem foi enviada.")
|
| 31 |
+
|
| 32 |
+
imagem = imagem.convert("RGB")
|
| 33 |
+
|
| 34 |
+
session = carregar_segmentador()
|
| 35 |
+
|
| 36 |
+
mascara = remove(
|
| 37 |
+
imagem,
|
| 38 |
+
session=session,
|
| 39 |
+
only_mask=True,
|
| 40 |
+
post_process_mask=True
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
if not isinstance(mascara, Image.Image):
|
| 44 |
+
mascara = Image.fromarray(
|
| 45 |
+
np.asarray(mascara)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
mascara = mascara.convert("L")
|
| 49 |
+
|
| 50 |
+
# Garante que a máscara tenha exatamente
|
| 51 |
+
# o mesmo tamanho da imagem original.
|
| 52 |
+
mascara = mascara.resize(
|
| 53 |
+
imagem.size,
|
| 54 |
+
Image.Resampling.LANCZOS
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
return mascara
|