Spaces:
Build error
Build error
Commit
·
ca08464
1
Parent(s):
7d9a54e
Mejorado diagnóstico con pruebas adicionales y cara realista
Browse files
app.py
CHANGED
|
@@ -1,6 +1,16 @@
|
|
| 1 |
# Simple app.py for Face Detection
|
| 2 |
import os
|
| 3 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# Comprobar y descargar modelos necesarios
|
| 6 |
try:
|
|
@@ -34,26 +44,43 @@ def modo_diagnostico():
|
|
| 34 |
for archivo in model_files:
|
| 35 |
if os.path.exists(archivo):
|
| 36 |
st.success(f"✅ Modelo encontrado: {archivo}")
|
|
|
|
| 37 |
else:
|
| 38 |
st.error(f"❌ Modelo NO encontrado: {archivo}")
|
| 39 |
|
| 40 |
# Probar carga del modelo
|
| 41 |
st.subheader("2. Prueba de carga del modelo")
|
| 42 |
try:
|
| 43 |
-
import cv2
|
| 44 |
-
import numpy as np
|
| 45 |
-
from PIL import Image
|
| 46 |
-
import io
|
| 47 |
-
import base64
|
| 48 |
-
|
| 49 |
modelFile = "res10_300x300_ssd_iter_140000.caffemodel"
|
| 50 |
configFile = "deploy.prototxt.txt"
|
| 51 |
|
| 52 |
-
|
| 53 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
# Crear imagen de prueba
|
| 56 |
-
st.subheader("3. Probar detección")
|
| 57 |
|
| 58 |
# Crear una imagen de prueba con un óvalo como rostro
|
| 59 |
example_image = np.zeros((400, 400, 3), dtype=np.uint8)
|
|
@@ -68,74 +95,233 @@ def modo_diagnostico():
|
|
| 68 |
# Mostrar imagen de prueba
|
| 69 |
st.image(example_image, caption="Imagen de prueba", channels="BGR")
|
| 70 |
|
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 |
-
y2 = max(0, min(y2, frame_h - 1))
|
| 98 |
-
|
| 99 |
-
# Verificar validez de la caja
|
| 100 |
-
width, height = x2 - x1, y2 - y1
|
| 101 |
-
if width <= 0 or height <= 0:
|
| 102 |
-
continue
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
if len(bboxes) == 0:
|
| 129 |
-
st.subheader("Posibles problemas:")
|
| 130 |
st.write("""
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
""")
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
except Exception as e:
|
| 138 |
-
st.error(f"Error en el diagnóstico: {e}")
|
| 139 |
|
| 140 |
# Crear un sidebar con opciones
|
| 141 |
st.sidebar.title("Opciones")
|
|
|
|
| 1 |
# Simple app.py for Face Detection
|
| 2 |
import os
|
| 3 |
import streamlit as st
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
# Configurar logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
# Comprobar y descargar modelos necesarios
|
| 16 |
try:
|
|
|
|
| 44 |
for archivo in model_files:
|
| 45 |
if os.path.exists(archivo):
|
| 46 |
st.success(f"✅ Modelo encontrado: {archivo}")
|
| 47 |
+
st.write(f"Tamaño: {os.path.getsize(archivo)} bytes")
|
| 48 |
else:
|
| 49 |
st.error(f"❌ Modelo NO encontrado: {archivo}")
|
| 50 |
|
| 51 |
# Probar carga del modelo
|
| 52 |
st.subheader("2. Prueba de carga del modelo")
|
| 53 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
modelFile = "res10_300x300_ssd_iter_140000.caffemodel"
|
| 55 |
configFile = "deploy.prototxt.txt"
|
| 56 |
|
| 57 |
+
# Cargar modelos
|
| 58 |
+
st.write("Intentando cargar el modelo DNN...")
|
| 59 |
+
try:
|
| 60 |
+
net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
|
| 61 |
+
st.success(f"✅ Modelo DNN cargado correctamente: {type(net)}")
|
| 62 |
+
st.write(f"Información del modelo: {str(net)}")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
st.error(f"❌ Error al cargar el modelo DNN: {e}")
|
| 65 |
+
st.warning("Intentando cargar cascadas Haar como alternativa...")
|
| 66 |
+
|
| 67 |
+
# Cargar cascadas Haar como alternativa
|
| 68 |
+
st.write("Cargando modelos de cascada Haar...")
|
| 69 |
+
try:
|
| 70 |
+
# Obtener la ruta a los archivos de cascada
|
| 71 |
+
haar_face_path = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
|
| 72 |
+
st.write(f"Ruta a Haar Cascade: {haar_face_path}")
|
| 73 |
+
haar_face = cv2.CascadeClassifier(haar_face_path)
|
| 74 |
+
|
| 75 |
+
if haar_face.empty():
|
| 76 |
+
st.error("❌ El clasificador de Haar no se cargó correctamente")
|
| 77 |
+
else:
|
| 78 |
+
st.success("✅ Cascada Haar para rostros cargada correctamente")
|
| 79 |
+
except Exception as e:
|
| 80 |
+
st.error(f"❌ Error al cargar cascadas Haar: {e}")
|
| 81 |
|
| 82 |
# Crear imagen de prueba
|
| 83 |
+
st.subheader("3. Probar detección con imagen sintética")
|
| 84 |
|
| 85 |
# Crear una imagen de prueba con un óvalo como rostro
|
| 86 |
example_image = np.zeros((400, 400, 3), dtype=np.uint8)
|
|
|
|
| 95 |
# Mostrar imagen de prueba
|
| 96 |
st.image(example_image, caption="Imagen de prueba", channels="BGR")
|
| 97 |
|
| 98 |
+
# Detectar rostros con DNN
|
| 99 |
+
st.subheader("4. Prueba de detección con DNN")
|
| 100 |
+
umbral = st.slider("Umbral de confianza DNN", 0.1, 0.9, 0.3, 0.1)
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
# Detectar rostros en la imagen de prueba con DNN
|
| 104 |
+
h, w = example_image.shape[:2]
|
| 105 |
+
blob = cv2.dnn.blobFromImage(cv2.resize(example_image, (300, 300)), 1.0,
|
| 106 |
+
(300, 300), (104.0, 177.0, 123.0))
|
| 107 |
+
|
| 108 |
+
net.setInput(blob)
|
| 109 |
+
detections = net.forward()
|
| 110 |
+
|
| 111 |
+
# Procesar detecciones
|
| 112 |
+
bboxes = []
|
| 113 |
+
frame_h, frame_w = example_image.shape[:2]
|
| 114 |
+
|
| 115 |
+
for i in range(detections.shape[2]):
|
| 116 |
+
confidence = detections[0, 0, i, 2]
|
| 117 |
+
|
| 118 |
+
if confidence > umbral:
|
| 119 |
+
box = detections[0, 0, i, 3:7] * np.array([frame_w, frame_h, frame_w, frame_h])
|
| 120 |
+
x1, y1, x2, y2 = box.astype("int")
|
| 121 |
+
|
| 122 |
+
# Asegurar coordenadas válidas
|
| 123 |
+
x1 = max(0, min(x1, frame_w - 1))
|
| 124 |
+
y1 = max(0, min(y1, frame_h - 1))
|
| 125 |
+
x2 = max(0, min(x2, frame_w - 1))
|
| 126 |
+
y2 = max(0, min(y2, frame_h - 1))
|
| 127 |
+
|
| 128 |
+
# Verificar validez de la caja
|
| 129 |
+
width, height = x2 - x1, y2 - y1
|
| 130 |
+
if width <= 0 or height <= 0:
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
bboxes.append([x1, y1, x2, y2, confidence])
|
| 134 |
+
|
| 135 |
+
# Dibujar resultados
|
| 136 |
+
result_image = example_image.copy()
|
| 137 |
+
for bbox in bboxes:
|
| 138 |
+
x1, y1, x2, y2, confidence = bbox
|
| 139 |
+
# Dibujar rectángulo verde grueso
|
| 140 |
+
cv2.rectangle(result_image, (x1, y1), (x2, y2), (0, 255, 0), 3)
|
| 141 |
+
# Añadir texto con confianza
|
| 142 |
+
cv2.putText(result_image, f"{confidence:.2f}", (x1, y1-10),
|
| 143 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
| 144 |
+
|
| 145 |
+
st.image(result_image, caption=f"Resultado con DNN (umbral {umbral})", channels="BGR")
|
| 146 |
+
|
| 147 |
+
# Mostrar estadísticas
|
| 148 |
+
st.write(f"Detecciones encontradas con DNN: {len(bboxes)}")
|
| 149 |
+
|
| 150 |
+
if len(bboxes) > 0:
|
| 151 |
+
st.success("✅ La detección DNN funciona correctamente")
|
| 152 |
+
else:
|
| 153 |
+
st.error("❌ No se detectaron rostros con DNN")
|
| 154 |
+
|
| 155 |
+
# Mostrar valores de confianza
|
| 156 |
+
st.write("Valores de confianza detectados:")
|
| 157 |
+
confianzas = []
|
| 158 |
+
for i in range(min(10, detections.shape[2])):
|
| 159 |
+
confianza = detections[0, 0, i, 2]
|
| 160 |
+
confianzas.append(confianza)
|
| 161 |
+
st.write(confianzas)
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
st.error(f"Error en detección DNN: {e}")
|
| 165 |
+
|
| 166 |
+
# Prueba con Haar Cascade
|
| 167 |
+
st.subheader("5. Prueba de detección con Haar (alternativa)")
|
| 168 |
+
try:
|
| 169 |
+
# Convertir a escala de grises
|
| 170 |
+
gray = cv2.cvtColor(example_image, cv2.COLOR_BGR2GRAY)
|
| 171 |
+
|
| 172 |
+
# Detectar rostros
|
| 173 |
+
faces = haar_face.detectMultiScale(
|
| 174 |
+
gray,
|
| 175 |
+
scaleFactor=1.1,
|
| 176 |
+
minNeighbors=5,
|
| 177 |
+
minSize=(30, 30),
|
| 178 |
+
flags=cv2.CASCADE_SCALE_IMAGE
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Dibujar resultados
|
| 182 |
+
haar_result = example_image.copy()
|
| 183 |
+
for (x, y, w, h) in faces:
|
| 184 |
+
cv2.rectangle(haar_result, (x, y), (x+w, y+h), (0, 255, 0), 3)
|
| 185 |
+
|
| 186 |
+
st.image(haar_result, caption="Resultado con Haar Cascade", channels="BGR")
|
| 187 |
+
|
| 188 |
+
st.write(f"Rostros detectados con Haar: {len(faces)}")
|
| 189 |
+
|
| 190 |
+
if len(faces) > 0:
|
| 191 |
+
st.success("✅ La detección con Haar funciona correctamente")
|
| 192 |
+
else:
|
| 193 |
+
st.error("❌ No se detectaron rostros con Haar")
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
st.error(f"Error en detección Haar: {e}")
|
| 197 |
+
|
| 198 |
+
# Probar con imagen real
|
| 199 |
+
st.subheader("6. Prueba con imagen de rostro real")
|
| 200 |
+
|
| 201 |
+
# Crear una imagen realista de prueba
|
| 202 |
+
real_face = np.ones((400, 400, 3), dtype=np.uint8) * 200 # Fondo gris claro
|
| 203 |
+
|
| 204 |
+
# Dibujar un rostro más realista (óvalo de color piel)
|
| 205 |
+
cv2.ellipse(real_face, (200, 200), (120, 170), 0, 0, 360, (50, 140, 220), -1) # BGR
|
| 206 |
|
| 207 |
+
# Dibujar ojos (elipses con iris y pupilas)
|
| 208 |
+
# Ojo izquierdo
|
| 209 |
+
cv2.ellipse(real_face, (150, 150), (25, 15), 0, 0, 360, (255, 255, 255), -1) # Blanco del ojo
|
| 210 |
+
cv2.circle(real_face, (150, 150), 10, (80, 120, 180), -1) # Iris
|
| 211 |
+
cv2.circle(real_face, (150, 150), 5, (20, 20, 20), -1) # Pupila
|
| 212 |
|
| 213 |
+
# Ojo derecho
|
| 214 |
+
cv2.ellipse(real_face, (250, 150), (25, 15), 0, 0, 360, (255, 255, 255), -1) # Blanco del ojo
|
| 215 |
+
cv2.circle(real_face, (250, 150), 10, (80, 120, 180), -1) # Iris
|
| 216 |
+
cv2.circle(real_face, (250, 150), 5, (20, 20, 20), -1) # Pupila
|
| 217 |
|
| 218 |
+
# Dibujar nariz
|
| 219 |
+
nose_points = np.array([[200, 180], [180, 220], [220, 220]], np.int32)
|
| 220 |
+
nose_points = nose_points.reshape((-1, 1, 2))
|
| 221 |
+
cv2.fillPoly(real_face, [nose_points], (40, 120, 200))
|
| 222 |
|
| 223 |
+
# Dibujar boca (sonrisa)
|
| 224 |
+
cv2.ellipse(real_face, (200, 260), (60, 25), 0, 0, 180, (40, 80, 200), -1)
|
| 225 |
+
|
| 226 |
+
# Mostrar imagen
|
| 227 |
+
st.image(real_face, caption="Imagen realista de prueba", channels="BGR")
|
| 228 |
+
|
| 229 |
+
# Detectar rostros con DNN en la imagen realista
|
| 230 |
+
try:
|
| 231 |
+
h, w = real_face.shape[:2]
|
| 232 |
+
blob = cv2.dnn.blobFromImage(cv2.resize(real_face, (300, 300)), 1.0,
|
| 233 |
+
(300, 300), (104.0, 177.0, 123.0))
|
| 234 |
|
| 235 |
+
net.setInput(blob)
|
| 236 |
+
detections = net.forward()
|
| 237 |
+
|
| 238 |
+
bboxes = []
|
| 239 |
+
for i in range(detections.shape[2]):
|
| 240 |
+
confidence = detections[0, 0, i, 2]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
+
if confidence > umbral:
|
| 243 |
+
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
|
| 244 |
+
x1, y1, x2, y2 = box.astype("int")
|
| 245 |
+
|
| 246 |
+
# Asegurar coordenadas válidas
|
| 247 |
+
x1 = max(0, min(x1, w - 1))
|
| 248 |
+
y1 = max(0, min(y1, h - 1))
|
| 249 |
+
x2 = max(0, min(x2, w - 1))
|
| 250 |
+
y2 = max(0, min(y2, h - 1))
|
| 251 |
+
|
| 252 |
+
# Verificar validez de la caja
|
| 253 |
+
width, height = x2 - x1, y2 - y1
|
| 254 |
+
if width <= 0 or height <= 0:
|
| 255 |
+
continue
|
| 256 |
+
|
| 257 |
+
bboxes.append([x1, y1, x2, y2, confidence])
|
| 258 |
+
|
| 259 |
+
# Dibujar resultados
|
| 260 |
+
real_result = real_face.copy()
|
| 261 |
+
for bbox in bboxes:
|
| 262 |
+
x1, y1, x2, y2, confidence = bbox
|
| 263 |
+
# Dibujar rectángulo verde grueso
|
| 264 |
+
cv2.rectangle(real_result, (x1, y1), (x2, y2), (0, 255, 0), 3)
|
| 265 |
+
# Añadir texto con confianza
|
| 266 |
+
cv2.putText(real_result, f"{confidence:.2f}", (x1, y1-10),
|
| 267 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
| 268 |
|
| 269 |
+
st.image(real_result, caption=f"Imagen realista con DNN (umbral {umbral})", channels="BGR")
|
| 270 |
+
|
| 271 |
+
st.write(f"Detecciones en imagen realista: {len(bboxes)}")
|
| 272 |
+
|
| 273 |
+
if len(bboxes) > 0:
|
| 274 |
+
st.success("✅ La detección en imagen realista funciona correctamente")
|
| 275 |
+
else:
|
| 276 |
+
st.error("❌ No se detectaron rostros en la imagen realista")
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
st.error(f"Error en detección de imagen realista: {e}")
|
| 280 |
+
|
| 281 |
+
# Diagnóstico final
|
| 282 |
+
st.subheader("Diagnóstico y recomendaciones")
|
| 283 |
+
|
| 284 |
if len(bboxes) == 0:
|
|
|
|
| 285 |
st.write("""
|
| 286 |
+
### Posibles problemas:
|
| 287 |
+
|
| 288 |
+
1. **El modelo no se está cargando correctamente.**
|
| 289 |
+
- Verifique que los archivos existan y tengan el tamaño correcto.
|
| 290 |
+
- Intente descargar los modelos manualmente en la misma carpeta.
|
| 291 |
+
|
| 292 |
+
2. **El procesamiento de la imagen es incorrecto.**
|
| 293 |
+
- La transformación blob podría estar mal configurada.
|
| 294 |
+
- Intente usar diferentes preprocesamiento de la imagen.
|
| 295 |
+
|
| 296 |
+
3. **El umbral de confianza es demasiado alto.**
|
| 297 |
+
- Pruebe umbrales más bajos como 0.1 o 0.2.
|
| 298 |
+
- Ajuste la sensibilidad de detección.
|
| 299 |
+
|
| 300 |
+
4. **Hay un problema con la visualización de los resultados.**
|
| 301 |
+
- Verifique el código que dibuja los rectángulos.
|
| 302 |
+
- Asegúrese de que las coordenadas sean válidas.
|
| 303 |
+
|
| 304 |
+
### Soluciones para la aplicación principal:
|
| 305 |
+
|
| 306 |
+
1. Intente usar Haar Cascades en lugar del modelo DNN.
|
| 307 |
+
2. Ajuste el umbral de confianza a un valor más bajo.
|
| 308 |
+
3. Verifique la conversión de color BGR a RGB en la visualización.
|
| 309 |
+
4. Intente usar otro modelo de detección facial como MediaPipe.
|
| 310 |
""")
|
| 311 |
+
else:
|
| 312 |
+
st.write("""
|
| 313 |
+
### La detección facial funciona en el diagnóstico, pero no en la aplicación principal
|
| 314 |
+
|
| 315 |
+
Esto sugiere que hay algún problema en la aplicación principal, no en el modelo. Revise:
|
| 316 |
+
|
| 317 |
+
1. Cómo se procesan las imágenes en la aplicación principal
|
| 318 |
+
2. El código que dibuja los rectángulos verdes
|
| 319 |
+
3. La conversión de color BGR a RGB para visualización
|
| 320 |
+
4. Los umbrales de confianza utilizados
|
| 321 |
+
""")
|
| 322 |
+
|
| 323 |
except Exception as e:
|
| 324 |
+
st.error(f"Error general en el diagnóstico: {e}")
|
| 325 |
|
| 326 |
# Crear un sidebar con opciones
|
| 327 |
st.sidebar.title("Opciones")
|