Spaces:
Sleeping
Sleeping
Commit ·
e918e2d
1
Parent(s): be3fab7
feat(face-recognition): implement facial recognition system with streamlit UI
Browse files- Dockerfile +1 -1
- face_recognition_app.py +334 -0
- requirements.txt +12 -3
- src/streamlit_app.py +0 -40
- streamlit_app.py +105 -0
Dockerfile
CHANGED
|
@@ -17,4 +17,4 @@ EXPOSE 8501
|
|
| 17 |
|
| 18 |
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
|
| 19 |
|
| 20 |
-
ENTRYPOINT ["streamlit", "run", "
|
|
|
|
| 17 |
|
| 18 |
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
|
| 19 |
|
| 20 |
+
ENTRYPOINT ["streamlit", "run", "streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
|
face_recognition_app.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Aplicativo simples de reconhecimento facial (coleta + treino + predição).
|
| 4 |
+
|
| 5 |
+
Fluxo:
|
| 6 |
+
1) O usuário envia quantas imagens quiser e informa o nome/pessoa a que cada imagem pertence.
|
| 7 |
+
2) O script recorta a(s) face(s) detectada(s) e armazena em `dataset/<nome>/`.
|
| 8 |
+
3) Quando o usuário digitar `done`, o script treina um reconhecedor (LBPH por padrão; opcional CNN se TensorFlow estiver disponível).
|
| 9 |
+
4) Por fim, o usuário fornece uma imagem para reconhecimento; o script identifica e salva `output.jpg` com anotações.
|
| 10 |
+
|
| 11 |
+
Requisitos: `opencv-contrib-python`, `numpy`. Opcional: `mtcnn` para detecção baseada em rede e `tensorflow` para classificação CNN.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import cv2
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pickle
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
try:
|
| 21 |
+
from mtcnn import MTCNN
|
| 22 |
+
HAS_MTCNN = True
|
| 23 |
+
except Exception:
|
| 24 |
+
HAS_MTCNN = False
|
| 25 |
+
try:
|
| 26 |
+
import tensorflow as tf
|
| 27 |
+
from tensorflow import keras
|
| 28 |
+
HAS_TF = True
|
| 29 |
+
except Exception:
|
| 30 |
+
HAS_TF = False
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
CASCADE_PATH = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
|
| 34 |
+
LBPH_CONFIDENCE_THRESHOLD = 80.0
|
| 35 |
+
USE_TF_DETECTOR = os.environ.get('FACE_USE_TF_DETECTOR', '1' if HAS_MTCNN else '0').lower() in ('1', 'true', 'yes')
|
| 36 |
+
mtcnn_detector = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def ensure_dirs():
|
| 40 |
+
Path('dataset').mkdir(exist_ok=True)
|
| 41 |
+
Path('trainer').mkdir(exist_ok=True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def detect_faces(image, scaleFactor=1.3, minNeighbors=5):
|
| 45 |
+
global mtcnn_detector
|
| 46 |
+
if USE_TF_DETECTOR and HAS_MTCNN:
|
| 47 |
+
if mtcnn_detector is None:
|
| 48 |
+
mtcnn_detector = MTCNN()
|
| 49 |
+
if len(image.shape) == 2:
|
| 50 |
+
image_bgr = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
|
| 51 |
+
else:
|
| 52 |
+
image_bgr = image
|
| 53 |
+
results = mtcnn_detector.detect_faces(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB))
|
| 54 |
+
faces = []
|
| 55 |
+
for r in results:
|
| 56 |
+
x, y, w, h = r.get('box', [0, 0, 0, 0])
|
| 57 |
+
x = max(0, int(x))
|
| 58 |
+
y = max(0, int(y))
|
| 59 |
+
w = max(1, int(w))
|
| 60 |
+
h = max(1, int(h))
|
| 61 |
+
faces.append((x, y, w, h))
|
| 62 |
+
return faces
|
| 63 |
+
else:
|
| 64 |
+
gray = image if len(image.shape) == 2 else cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 65 |
+
detector = cv2.CascadeClassifier(CASCADE_PATH)
|
| 66 |
+
faces = detector.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=minNeighbors)
|
| 67 |
+
return faces
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def is_image_file(path):
|
| 71 |
+
ext = str(path).lower()
|
| 72 |
+
return ext.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.tiff'))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def collect_images_interactive():
|
| 76 |
+
print('\n--- Coleta de imagens para treinamento ---')
|
| 77 |
+
print('Digite o caminho da foto ou da pasta com fotos, ou `done`.')
|
| 78 |
+
print('Informe o nome da pessoa correspondente. Se houver várias faces, escolha um índice ou digite `all`.')
|
| 79 |
+
|
| 80 |
+
while True:
|
| 81 |
+
src_path = input('\nCaminho da foto/pasta (ou done): ').strip()
|
| 82 |
+
if src_path.lower() in ('done', 'd'):
|
| 83 |
+
break
|
| 84 |
+
if not os.path.exists(src_path):
|
| 85 |
+
print('Arquivo/pasta não encontrada, tente novamente.')
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
if os.path.isdir(src_path):
|
| 89 |
+
name = input('Nome da pessoa para todas as fotos desta pasta: ').strip()
|
| 90 |
+
if not name:
|
| 91 |
+
print('Nome inválido, tente novamente.')
|
| 92 |
+
continue
|
| 93 |
+
files = [str(p) for p in Path(src_path).glob('*') if is_image_file(str(p))]
|
| 94 |
+
if not files:
|
| 95 |
+
print('Nenhuma imagem encontrada na pasta.')
|
| 96 |
+
continue
|
| 97 |
+
for img_path in files:
|
| 98 |
+
image = cv2.imread(img_path)
|
| 99 |
+
if image is None:
|
| 100 |
+
continue
|
| 101 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 102 |
+
faces = detect_faces(gray)
|
| 103 |
+
if len(faces) == 0:
|
| 104 |
+
continue
|
| 105 |
+
if len(faces) > 1:
|
| 106 |
+
print(f'{Path(img_path).name}: {len(faces)} faces detectadas.')
|
| 107 |
+
for i, (x, y, w, h) in enumerate(faces):
|
| 108 |
+
print(f' [{i}] x={x} y={y} w={w} h={h}')
|
| 109 |
+
choice = input('Índice a salvar ou `all` para todas (enter para 0): ').strip().lower()
|
| 110 |
+
if choice in ('all', 'a'):
|
| 111 |
+
idxs = list(range(len(faces)))
|
| 112 |
+
elif choice == '':
|
| 113 |
+
idxs = [0]
|
| 114 |
+
else:
|
| 115 |
+
try:
|
| 116 |
+
idxs = [int(choice)]
|
| 117 |
+
except Exception:
|
| 118 |
+
idxs = [0]
|
| 119 |
+
else:
|
| 120 |
+
idxs = [0]
|
| 121 |
+
for idx in idxs:
|
| 122 |
+
x, y, w, h = faces[idx]
|
| 123 |
+
face_img = gray[y:y+h, x:x+w]
|
| 124 |
+
face_img = cv2.resize(face_img, (200, 200))
|
| 125 |
+
person_dir = Path('dataset') / name
|
| 126 |
+
person_dir.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
next_i = len(list(person_dir.glob('*.jpg')))
|
| 128 |
+
out_path = person_dir / f'{next_i:03d}.jpg'
|
| 129 |
+
cv2.imwrite(str(out_path), face_img)
|
| 130 |
+
print(f'Salvo {out_path}')
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
name = input('Nome da pessoa para essa foto: ').strip()
|
| 134 |
+
if not name:
|
| 135 |
+
print('Nome inválido, tente novamente.')
|
| 136 |
+
continue
|
| 137 |
+
image = cv2.imread(src_path)
|
| 138 |
+
if image is None:
|
| 139 |
+
print('Não foi possível ler a imagem, pulei.')
|
| 140 |
+
continue
|
| 141 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 142 |
+
faces = detect_faces(gray)
|
| 143 |
+
if len(faces) == 0:
|
| 144 |
+
print('Nenhuma face detectada nesta imagem. Pulei.')
|
| 145 |
+
continue
|
| 146 |
+
idxs = [0]
|
| 147 |
+
if len(faces) > 1:
|
| 148 |
+
print(f'Foram detectadas {len(faces)} faces nesta imagem.')
|
| 149 |
+
for i, (x, y, w, h) in enumerate(faces):
|
| 150 |
+
print(f' [{i}] x={x} y={y} w={w} h={h}')
|
| 151 |
+
choice = input('Índice a salvar ou `all` para todas (enter para 0): ').strip().lower()
|
| 152 |
+
if choice in ('all', 'a'):
|
| 153 |
+
idxs = list(range(len(faces)))
|
| 154 |
+
elif choice == '':
|
| 155 |
+
idxs = [0]
|
| 156 |
+
else:
|
| 157 |
+
try:
|
| 158 |
+
idxs = [int(choice)]
|
| 159 |
+
except Exception:
|
| 160 |
+
idxs = [0]
|
| 161 |
+
for idx in idxs:
|
| 162 |
+
x, y, w, h = faces[idx]
|
| 163 |
+
face_img = gray[y:y+h, x:x+w]
|
| 164 |
+
face_img = cv2.resize(face_img, (200, 200))
|
| 165 |
+
person_dir = Path('dataset') / name
|
| 166 |
+
person_dir.mkdir(parents=True, exist_ok=True)
|
| 167 |
+
next_i = len(list(person_dir.glob('*.jpg')))
|
| 168 |
+
out_path = person_dir / f'{next_i:03d}.jpg'
|
| 169 |
+
cv2.imwrite(str(out_path), face_img)
|
| 170 |
+
print(f'Salvo {out_path}')
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def train_recognizer(method='lbph', progress_callback=None):
|
| 174 |
+
if progress_callback: progress_callback('Iniciando treinamento...')
|
| 175 |
+
dataset_dir = Path('dataset')
|
| 176 |
+
if not dataset_dir.exists():
|
| 177 |
+
print('Pasta dataset/ não encontrada. Colete imagens primeiro.')
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
faces = []
|
| 181 |
+
labels = []
|
| 182 |
+
label_ids = {}
|
| 183 |
+
current_id = 0
|
| 184 |
+
|
| 185 |
+
for person_dir in sorted(dataset_dir.iterdir()):
|
| 186 |
+
if not person_dir.is_dir():
|
| 187 |
+
continue
|
| 188 |
+
name = person_dir.name
|
| 189 |
+
if name not in label_ids:
|
| 190 |
+
label_ids[name] = current_id
|
| 191 |
+
current_id += 1
|
| 192 |
+
id_ = label_ids[name]
|
| 193 |
+
for img_path in person_dir.glob('*.jpg'):
|
| 194 |
+
img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE)
|
| 195 |
+
if img is None:
|
| 196 |
+
continue
|
| 197 |
+
faces.append(img)
|
| 198 |
+
labels.append(id_)
|
| 199 |
+
|
| 200 |
+
if len(faces) == 0:
|
| 201 |
+
print('Nenhuma imagem para treinar. Adicione fotos ao dataset/.')
|
| 202 |
+
return False
|
| 203 |
+
|
| 204 |
+
method = (method or 'lbph').strip().lower()
|
| 205 |
+
if method == 'cnn':
|
| 206 |
+
if not HAS_TF:
|
| 207 |
+
print('TensorFlow não disponível. Instale `tensorflow` ou escolha LBPH.')
|
| 208 |
+
return False
|
| 209 |
+
X = np.stack([f for f in faces]).astype('float32') / 255.0
|
| 210 |
+
X = np.expand_dims(X, -1)
|
| 211 |
+
y = np.array(labels, dtype=np.int32)
|
| 212 |
+
num_classes = len(set(labels))
|
| 213 |
+
model = keras.Sequential([
|
| 214 |
+
keras.layers.Input(shape=(200, 200, 1)),
|
| 215 |
+
keras.layers.Conv2D(16, 3, activation='relu'),
|
| 216 |
+
keras.layers.MaxPooling2D(),
|
| 217 |
+
keras.layers.Conv2D(32, 3, activation='relu'),
|
| 218 |
+
keras.layers.MaxPooling2D(),
|
| 219 |
+
keras.layers.Conv2D(64, 3, activation='relu'),
|
| 220 |
+
keras.layers.MaxPooling2D(),
|
| 221 |
+
keras.layers.Flatten(),
|
| 222 |
+
keras.layers.Dense(128, activation='relu'),
|
| 223 |
+
keras.layers.Dense(num_classes, activation='softmax'),
|
| 224 |
+
])
|
| 225 |
+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
| 226 |
+
if progress_callback: progress_callback('Treinando CNN (isso pode demorar)...')
|
| 227 |
+
model.fit(X, y, epochs=10, batch_size=16, verbose=1)
|
| 228 |
+
model_path = Path('trainer') / 'model_tf.h5'
|
| 229 |
+
model.save(str(model_path))
|
| 230 |
+
with open('trainer/labels.pickle', 'wb') as f:
|
| 231 |
+
pickle.dump(label_ids, f)
|
| 232 |
+
print(f'Treino finalizado. Modelo salvo em {model_path} e labels em trainer/labels.pickle')
|
| 233 |
+
return True
|
| 234 |
+
else:
|
| 235 |
+
try:
|
| 236 |
+
recognizer = cv2.face.LBPHFaceRecognizer_create()
|
| 237 |
+
except Exception:
|
| 238 |
+
print('ERRO: cv2.face não disponível. Instale `opencv-contrib-python` e tente novamente.')
|
| 239 |
+
return False
|
| 240 |
+
recognizer.train(faces, np.array(labels))
|
| 241 |
+
model_path = Path('trainer') / 'trainer.yml'
|
| 242 |
+
recognizer.write(str(model_path))
|
| 243 |
+
with open('trainer/labels.pickle', 'wb') as f:
|
| 244 |
+
pickle.dump(label_ids, f)
|
| 245 |
+
print(f'Treino finalizado. Modelo salvo em {model_path} e labels em trainer/labels.pickle')
|
| 246 |
+
return True
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def predict_on_image(input_image=None):
|
| 250 |
+
labels_path = Path('trainer') / 'labels.pickle'
|
| 251 |
+
model_tf_path = Path('trainer') / 'model_tf.h5'
|
| 252 |
+
model_lbph_path = Path('trainer') / 'trainer.yml'
|
| 253 |
+
if not labels_path.exists() or (not model_tf_path.exists() and not model_lbph_path.exists()):
|
| 254 |
+
print('Modelo não encontrado. Treine primeiro usando a etapa de coleta e treino.')
|
| 255 |
+
return None
|
| 256 |
+
|
| 257 |
+
with open(labels_path, 'rb') as f:
|
| 258 |
+
label_ids = pickle.load(f)
|
| 259 |
+
id_labels = {v: k for k, v in label_ids.items()}
|
| 260 |
+
|
| 261 |
+
use_tf = HAS_TF and model_tf_path.exists()
|
| 262 |
+
if use_tf:
|
| 263 |
+
model = keras.models.load_model(str(model_tf_path))
|
| 264 |
+
else:
|
| 265 |
+
try:
|
| 266 |
+
recognizer = cv2.face.LBPHFaceRecognizer_create()
|
| 267 |
+
except Exception:
|
| 268 |
+
print('ERRO: cv2.face não disponível. Instale `opencv-contrib-python` ou treine com CNN.')
|
| 269 |
+
return None
|
| 270 |
+
recognizer.read(str(model_lbph_path))
|
| 271 |
+
|
| 272 |
+
if input_image is None:
|
| 273 |
+
img_path = input('\nCaminho da imagem para reconhecer: ').strip()
|
| 274 |
+
if not os.path.exists(img_path):
|
| 275 |
+
print('Arquivo não encontrado.')
|
| 276 |
+
return None
|
| 277 |
+
image = cv2.imread(img_path)
|
| 278 |
+
else:
|
| 279 |
+
image = input_image
|
| 280 |
+
|
| 281 |
+
if image is None:
|
| 282 |
+
print('Erro ao ler a imagem.')
|
| 283 |
+
return None
|
| 284 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 285 |
+
faces = detect_faces(gray)
|
| 286 |
+
if len(faces) == 0:
|
| 287 |
+
print('Nenhuma face detectada na imagem de teste.')
|
| 288 |
+
return
|
| 289 |
+
for (x, y, w, h) in faces:
|
| 290 |
+
face_img = gray[y:y+h, x:x+w]
|
| 291 |
+
try:
|
| 292 |
+
face_img = cv2.resize(face_img, (200, 200))
|
| 293 |
+
except Exception:
|
| 294 |
+
pass
|
| 295 |
+
if use_tf:
|
| 296 |
+
arr = (face_img.astype('float32') / 255.0)[None, ..., None]
|
| 297 |
+
probs = model.predict(arr, verbose=0)[0]
|
| 298 |
+
label_id = int(np.argmax(probs))
|
| 299 |
+
confidence = float(np.max(probs) * 100.0)
|
| 300 |
+
name = id_labels.get(label_id, 'desconhecido')
|
| 301 |
+
text = f'{name} ({confidence:.1f}%)'
|
| 302 |
+
else:
|
| 303 |
+
label_id, confidence = recognizer.predict(face_img)
|
| 304 |
+
name = id_labels.get(label_id, 'desconhecido')
|
| 305 |
+
if confidence > LBPH_CONFIDENCE_THRESHOLD:
|
| 306 |
+
name = 'desconhecido'
|
| 307 |
+
text = f'{name} ({confidence:.1f})'
|
| 308 |
+
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
|
| 309 |
+
cv2.putText(image, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
| 310 |
+
out_path = 'output.jpg'
|
| 311 |
+
cv2.imwrite(out_path, image)
|
| 312 |
+
print(f'Resultado salvo em {out_path}.')
|
| 313 |
+
return image
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def main():
|
| 317 |
+
ensure_dirs()
|
| 318 |
+
print('Aplicativo de reconhecimento facial — coleta, treino e predição')
|
| 319 |
+
print('Certifique-se de ter instalado: opencv-contrib-python, numpy')
|
| 320 |
+
if USE_TF_DETECTOR and HAS_MTCNN:
|
| 321 |
+
print('Detecção: MTCNN')
|
| 322 |
+
else:
|
| 323 |
+
print('Detecção: Haar Cascade')
|
| 324 |
+
collect_images_interactive()
|
| 325 |
+
method_in = input('Método de classificação [lbph/cnn] (padrão lbph): ').strip().lower()
|
| 326 |
+
if method_in not in ('lbph', 'cnn'):
|
| 327 |
+
method_in = 'lbph'
|
| 328 |
+
trained = train_recognizer(method_in)
|
| 329 |
+
if trained:
|
| 330 |
+
predict_on_image()
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
if __name__ == '__main__':
|
| 334 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,3 +1,12 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ipywidgets==8.1.2
|
| 2 |
+
matplotlib==3.8.4
|
| 3 |
+
pandas==2.2.2
|
| 4 |
+
torch==2.8.0
|
| 5 |
+
torchvision==0.23.0
|
| 6 |
+
tqdm==4.66.4
|
| 7 |
+
|
| 8 |
+
# Adicionados para o projeto de reconhecimento facial
|
| 9 |
+
opencv-contrib-python==4.8.0.76
|
| 10 |
+
numpy==1.26.4
|
| 11 |
+
streamlit
|
| 12 |
+
pillow
|
src/streamlit_app.py
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import streamlit as st
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
# Welcome to Streamlit!
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
streamlit_app.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import os
|
| 7 |
+
from face_recognition_app import ensure_dirs, detect_faces, train_recognizer, predict_on_image, HAS_TF
|
| 8 |
+
|
| 9 |
+
# Configuração da página
|
| 10 |
+
st.set_page_config(page_title="Reconhecimento Facial", layout="wide")
|
| 11 |
+
ensure_dirs()
|
| 12 |
+
|
| 13 |
+
st.title("Sistema de Reconhecimento Facial")
|
| 14 |
+
|
| 15 |
+
# Sidebar para navegação
|
| 16 |
+
menu = st.sidebar.selectbox("Menu", ["Coleta de Dados", "Treinamento", "Reconhecimento"])
|
| 17 |
+
|
| 18 |
+
if menu == "Coleta de Dados":
|
| 19 |
+
st.header("1. Coleta de Imagens para o Dataset")
|
| 20 |
+
|
| 21 |
+
person_name = st.text_input("Nome da Pessoa:")
|
| 22 |
+
uploaded_files = st.file_uploader("Escolha imagens...", accept_multiple_files=True, type=['jpg', 'jpeg', 'png'])
|
| 23 |
+
|
| 24 |
+
if st.button("Processar e Salvar Faces"):
|
| 25 |
+
if not person_name:
|
| 26 |
+
st.error("Por favor, informe o nome da pessoa.")
|
| 27 |
+
elif not uploaded_files:
|
| 28 |
+
st.error("Por favor, selecione pelo menos uma imagem.")
|
| 29 |
+
else:
|
| 30 |
+
progress_bar = st.progress(0)
|
| 31 |
+
person_dir = Path('dataset') / person_name
|
| 32 |
+
person_dir.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
|
| 34 |
+
saved_count = 0
|
| 35 |
+
for i, uploaded_file in enumerate(uploaded_files):
|
| 36 |
+
# Converter arquivo para imagem OpenCV
|
| 37 |
+
file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
|
| 38 |
+
image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
|
| 39 |
+
|
| 40 |
+
if image is not None:
|
| 41 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 42 |
+
faces = detect_faces(gray)
|
| 43 |
+
|
| 44 |
+
for (x, y, w, h) in faces:
|
| 45 |
+
face_img = gray[y:y+h, x:x+w]
|
| 46 |
+
face_img = cv2.resize(face_img, (200, 200))
|
| 47 |
+
|
| 48 |
+
next_i = len(list(person_dir.glob('*.jpg')))
|
| 49 |
+
out_path = person_dir / f'{next_i:03d}.jpg'
|
| 50 |
+
cv2.imwrite(str(out_path), face_img)
|
| 51 |
+
saved_count += 1
|
| 52 |
+
|
| 53 |
+
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 54 |
+
|
| 55 |
+
st.success(f"Processamento concluído! {saved_count} faces salvas para '{person_name}'.")
|
| 56 |
+
|
| 57 |
+
elif menu == "Treinamento":
|
| 58 |
+
st.header("2. Treinar o Modelo")
|
| 59 |
+
|
| 60 |
+
dataset_path = Path('dataset')
|
| 61 |
+
if not dataset_path.exists() or not any(dataset_path.iterdir()):
|
| 62 |
+
st.warning("O dataset está vazio. Vá para 'Coleta de Dados' primeiro.")
|
| 63 |
+
else:
|
| 64 |
+
st.info("Pessoas encontradas no dataset:")
|
| 65 |
+
names = [d.name for d in dataset_path.iterdir() if d.is_dir()]
|
| 66 |
+
st.write(", ".join(names))
|
| 67 |
+
|
| 68 |
+
method = st.radio("Método de Treinamento:", ["LBPH", "CNN"] if HAS_TF else ["LBPH"])
|
| 69 |
+
|
| 70 |
+
if st.button("Iniciar Treinamento"):
|
| 71 |
+
status_text = st.empty()
|
| 72 |
+
|
| 73 |
+
def update_status(msg):
|
| 74 |
+
status_text.text(msg)
|
| 75 |
+
|
| 76 |
+
success = train_recognizer(method=method.lower(), progress_callback=update_status)
|
| 77 |
+
|
| 78 |
+
if success:
|
| 79 |
+
st.success("Modelo treinado com sucesso!")
|
| 80 |
+
else:
|
| 81 |
+
st.error("Erro durante o treinamento.")
|
| 82 |
+
|
| 83 |
+
elif menu == "Reconhecimento":
|
| 84 |
+
st.header("3. Reconhecimento Facial em Imagem")
|
| 85 |
+
|
| 86 |
+
labels_path = Path('trainer') / 'labels.pickle'
|
| 87 |
+
if not labels_path.exists():
|
| 88 |
+
st.warning("Nenhum modelo treinado encontrado. Vá para 'Treinamento' primeiro.")
|
| 89 |
+
else:
|
| 90 |
+
test_file = st.file_uploader("Escolha uma imagem para reconhecimento...", type=['jpg', 'jpeg', 'png'])
|
| 91 |
+
|
| 92 |
+
if test_file is not None:
|
| 93 |
+
# Converter para OpenCV
|
| 94 |
+
file_bytes = np.asarray(bytearray(test_file.read()), dtype=np.uint8)
|
| 95 |
+
image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
|
| 96 |
+
|
| 97 |
+
if st.button("Executar Reconhecimento"):
|
| 98 |
+
result_image = predict_on_image(input_image=image)
|
| 99 |
+
|
| 100 |
+
if result_image is not None:
|
| 101 |
+
# Converter BGR para RGB para o Streamlit
|
| 102 |
+
result_rgb = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)
|
| 103 |
+
st.image(result_rgb, caption="Resultado do Reconhecimento", use_container_width=True)
|
| 104 |
+
else:
|
| 105 |
+
st.error("Não foi possível processar a imagem ou nenhuma face foi detectada.")
|