Tentando segmentar novamente.
Browse files- Dockerfile +1 -0
- feature_extractor_single.py +42 -20
- requirements.txt +5 -1
- svm_model.pkl +2 -2
- umap_reducer.pkl +2 -2
Dockerfile
CHANGED
|
@@ -4,6 +4,7 @@ FROM python:3.10
|
|
| 4 |
#Variáveis de Ambiente para Caches
|
| 5 |
ENV HUGGINGFACE_HUB_CACHE="/tmp/huggingface"
|
| 6 |
ENV NUMBA_CACHE_DIR="/tmp/numba_cache"
|
|
|
|
| 7 |
|
| 8 |
#Define um diretório de trabalho limpo
|
| 9 |
WORKDIR /app
|
|
|
|
| 4 |
#Variáveis de Ambiente para Caches
|
| 5 |
ENV HUGGINGFACE_HUB_CACHE="/tmp/huggingface"
|
| 6 |
ENV NUMBA_CACHE_DIR="/tmp/numba_cache"
|
| 7 |
+
ENV U2NET_HOME="/tmp/u2net"
|
| 8 |
|
| 9 |
#Define um diretório de trabalho limpo
|
| 10 |
WORKDIR /app
|
feature_extractor_single.py
CHANGED
|
@@ -4,6 +4,7 @@ import numpy as np
|
|
| 4 |
from PIL import Image
|
| 5 |
from torchvision import transforms
|
| 6 |
from transformers import ConvNextImageProcessor, ConvNextForImageClassification
|
|
|
|
| 7 |
|
| 8 |
#Classe para extração de features (ConvNeXt)
|
| 9 |
class FeatureExtractor:
|
|
@@ -11,7 +12,7 @@ class FeatureExtractor:
|
|
| 11 |
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
print(f"Usando dispositivo: {self.device}")
|
| 13 |
|
| 14 |
-
#Modelo e pré-processador
|
| 15 |
self.processor = ConvNextImageProcessor.from_pretrained(
|
| 16 |
"facebook/convnext-large-224-22k-1k"
|
| 17 |
)
|
|
@@ -24,35 +25,56 @@ class FeatureExtractor:
|
|
| 24 |
self.model.eval()
|
| 25 |
|
| 26 |
def extract_convnext(self, image_path: str) -> np.ndarray:
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
with torch.no_grad():
|
| 30 |
features = self.model(**inputs).logits
|
|
|
|
| 31 |
features_np = features.cpu().numpy().flatten()
|
| 32 |
print(f"Vetor de características extraído com shape: {features_np.shape}")
|
|
|
|
| 33 |
return features_np
|
| 34 |
|
| 35 |
-
#Função principal
|
| 36 |
def process_single_image(image_path: str, output_dir: str = "processed"):
|
| 37 |
"""
|
| 38 |
-
|
| 39 |
"""
|
| 40 |
-
#1) Extração de features
|
| 41 |
extractor = FeatureExtractor()
|
| 42 |
-
#Passa o CAMINHO ORIGINAL da imagem (ex: /tmp/temp_foto.jpg)
|
| 43 |
features = extractor.extract_convnext(image_path)
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
#feat_path = os.path.join(output_dir, "features_single.npy")
|
| 47 |
-
#np.save(feat_path, features)
|
| 48 |
-
#print(f"Vetor de características salvo em: {feat_path}")
|
| 49 |
-
|
| 50 |
-
return features #RETORNA O ARRAY DE DADOS
|
| 51 |
-
|
| 52 |
-
#Execução direta
|
| 53 |
if __name__ == "__main__":
|
| 54 |
-
#
|
| 55 |
-
image_path =
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
from torchvision import transforms
|
| 6 |
from transformers import ConvNextImageProcessor, ConvNextForImageClassification
|
| 7 |
+
from rembg import remove
|
| 8 |
|
| 9 |
#Classe para extração de features (ConvNeXt)
|
| 10 |
class FeatureExtractor:
|
|
|
|
| 12 |
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
print(f"Usando dispositivo: {self.device}")
|
| 14 |
|
| 15 |
+
# Modelo e pré-processador
|
| 16 |
self.processor = ConvNextImageProcessor.from_pretrained(
|
| 17 |
"facebook/convnext-large-224-22k-1k"
|
| 18 |
)
|
|
|
|
| 25 |
self.model.eval()
|
| 26 |
|
| 27 |
def extract_convnext(self, image_path: str) -> np.ndarray:
|
| 28 |
+
#1. Abre a imagem original
|
| 29 |
+
print(f"Processando imagem: {os.path.basename(image_path)}")
|
| 30 |
+
input_img = Image.open(image_path).convert("RGB")
|
| 31 |
+
|
| 32 |
+
#2. SEGMENTAÇÃO (remoção do fundo)
|
| 33 |
+
#O rembg devolve uma imagem RGBA (com transparência)
|
| 34 |
+
try:
|
| 35 |
+
img_no_bg = remove(input_img)
|
| 36 |
+
|
| 37 |
+
#3. COMPOSIÇÃO EM FUNDO PRETO
|
| 38 |
+
#Cria uma imagem totalmente preta do mesmo tamanho
|
| 39 |
+
fundo_preto = Image.new("RGB", img_no_bg.size, (0, 0, 0))
|
| 40 |
+
|
| 41 |
+
#Usa o canal Alpha (transparência) da imagem recortada como máscara
|
| 42 |
+
#Onde for folha, cola a folha. Onde for transparente, mantém o preto.
|
| 43 |
+
mask = img_no_bg.split()[3] #Pega o 4º canal (Alpha)
|
| 44 |
+
fundo_preto.paste(img_no_bg, mask=mask)
|
| 45 |
+
|
| 46 |
+
final_image = fundo_preto
|
| 47 |
+
print("Fundo removido e substituído por preto com sucesso.")
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"AVISO: Falha na segmentação ({e}). Usando imagem original.")
|
| 51 |
+
final_image = input_img
|
| 52 |
+
|
| 53 |
+
#4. Passa para o ConvNeXt (que já faz o resize e normalize internamente)
|
| 54 |
+
inputs = self.processor(final_image, return_tensors="pt").to(self.device)
|
| 55 |
+
|
| 56 |
with torch.no_grad():
|
| 57 |
features = self.model(**inputs).logits
|
| 58 |
+
|
| 59 |
features_np = features.cpu().numpy().flatten()
|
| 60 |
print(f"Vetor de características extraído com shape: {features_np.shape}")
|
| 61 |
+
|
| 62 |
return features_np
|
| 63 |
|
| 64 |
+
#Função principal chamada pelo main.py
|
| 65 |
def process_single_image(image_path: str, output_dir: str = "processed"):
|
| 66 |
"""
|
| 67 |
+
Pipeline: Segmentação (Rembg) -> Fundo preto -> ConvNeXt
|
| 68 |
"""
|
|
|
|
| 69 |
extractor = FeatureExtractor()
|
|
|
|
| 70 |
features = extractor.extract_convnext(image_path)
|
| 71 |
+
return features
|
| 72 |
|
| 73 |
+
#Execução direta para testes locais
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
if __name__ == "__main__":
|
| 75 |
+
#Teste com uma imagem local
|
| 76 |
+
image_path = "teste_folha.jpg" #Mudar para um arquivo real se for testar
|
| 77 |
+
if os.path.exists(image_path):
|
| 78 |
+
process_single_image(image_path)
|
| 79 |
+
else:
|
| 80 |
+
print("Imagem de teste não encontrada.")
|
requirements.txt
CHANGED
|
@@ -20,4 +20,8 @@ umap-learn==0.5.6
|
|
| 20 |
joblib==1.4.2
|
| 21 |
|
| 22 |
#Utilitários gerais
|
| 23 |
-
requests==2.32.3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
joblib==1.4.2
|
| 21 |
|
| 22 |
#Utilitários gerais
|
| 23 |
+
requests==2.32.3
|
| 24 |
+
|
| 25 |
+
#Segmentação
|
| 26 |
+
rembg
|
| 27 |
+
onnxruntime
|
svm_model.pkl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7220864ee09603bf8abd9bd233a5bd0bf31e9eca496465973449887b4abcd8c6
|
| 3 |
+
size 3399533
|
umap_reducer.pkl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f454d8c21b3982fce91bcd2fb679c1ec9d0c9c326ea5059cccee799b58853b20
|
| 3 |
+
size 255570333
|