Segizu commited on
Commit
7823cea
·
1 Parent(s): 0d11749
Files changed (3) hide show
  1. app.py +50 -68
  2. apt.txt +0 -4
  3. requirements.txt +1 -6
app.py CHANGED
@@ -1,85 +1,67 @@
1
- import gradio as gr
2
- import face_recognition
3
- import numpy as np
4
  import os
 
5
  from PIL import Image
6
- import dlib
7
-
8
- # Verificar si CUDA está disponible y seleccionar el modelo adecuado
9
- if dlib.DLIB_USE_CUDA:
10
- print("✅ CUDA está disponible. Se usará GPU para reconocimiento facial.")
11
- model_used = "cnn" # Modelo optimizado para GPU
12
- else:
13
- print("⚠ CUDA no está disponible. Se usará CPU para reconocimiento facial.")
14
- model_used = "hog" # Modelo más adecuado para CPU
15
 
16
- # 📂 Directorio donde se encuentran las imágenes
17
  IMAGE_DIRECTORY = "dataset_faces/"
18
 
19
- def load_images_and_encodings(directory):
20
- """
21
- Carga las imágenes y extrae sus embeddings.
22
- """
23
- known_encodings = []
24
- known_images = []
25
- known_names = []
 
 
 
 
 
 
 
 
26
 
27
- for filename in os.listdir(directory):
28
- if filename.lower().endswith((".jpg", ".png", ".jpeg")):
29
- path = os.path.join(directory, filename)
30
- image = face_recognition.load_image_file(path)
31
- encodings = face_recognition.face_encodings(image, model=model_used)
32
- if encodings: # Si se detecta al menos una cara
33
- known_encodings.append(encodings[0])
34
- known_images.append(path)
35
- known_names.append(filename)
36
- return known_encodings, known_images, known_names
37
 
38
- # Cargar los datos de la carpeta de imágenes
39
- known_encodings, known_images, known_names = load_images_and_encodings(IMAGE_DIRECTORY)
 
 
 
40
 
41
- def find_similar_faces_gradio(uploaded_image):
42
- """
43
- Dada una imagen subida, busca las imágenes similares del dataset.
44
- Devuelve una lista de diccionarios para la galería y un texto con detalles.
45
- """
46
- if uploaded_image is None:
47
- return [], "No se subió ninguna imagen."
48
-
49
- # Convertir la imagen subida a array de NumPy
50
- image_np = np.array(uploaded_image)
51
- face_encodings = face_recognition.face_encodings(image_np, model=model_used)
52
- if not face_encodings:
53
- return [], "⚠ No se detectó ningún rostro en la imagen subida."
54
-
55
- query_encoding = face_encodings[0]
56
- distances = face_recognition.face_distance(known_encodings, query_encoding)
57
- sorted_indices = np.argsort(distances) # Ordenar por similitud (menor distancia = mayor similitud)
58
-
59
- # Mostrar las 5 imágenes más similares
60
- top_n = 5
61
  gallery_items = []
62
- details = ""
63
- for idx in sorted_indices[:top_n]:
64
- # Abrir la imagen del dataset
65
- img = Image.open(known_images[idx])
66
- similarity = 1 - distances[idx] # Definir similitud (valor entre 0 y 1)
67
- caption = f"{os.path.basename(known_images[idx])}: Similitud: {similarity:.2f}"
68
  gallery_items.append({"image": img, "caption": caption})
69
- details += caption + "\n"
70
-
71
- return gallery_items, details
72
 
73
- # Definir la interfaz con Gradio
74
  demo = gr.Interface(
75
- fn=find_similar_faces_gradio,
76
- inputs=gr.Image(label="Sube una imagen", type="pil"),
77
  outputs=[
78
- gr.Gallery(label="Imágenes similares").style(grid=[2], height="auto"),
79
- gr.Textbox(label="Detalles de similitud", lines=5)
80
  ],
81
- title="🔍 Buscador de Rostros en un Directorio",
82
- description="Sube una imagen y se mostrarán las fotos más similares del directorio."
83
  )
84
 
85
  demo.launch()
 
 
 
 
1
  import os
2
+ import numpy as np
3
  from PIL import Image
4
+ import gradio as gr
5
+ from deepface import DeepFace
 
 
 
 
 
 
 
6
 
7
+ # Ruta de la carpeta con rostros
8
  IMAGE_DIRECTORY = "dataset_faces/"
9
 
10
+ # Cargar embeddings de todas las imágenes del dataset
11
+ def build_database():
12
+ database = []
13
+ for filename in os.listdir(IMAGE_DIRECTORY):
14
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
15
+ path = os.path.join(IMAGE_DIRECTORY, filename)
16
+ try:
17
+ representation = DeepFace.represent(img_path=path, model_name="Facenet")[0]["embedding"]
18
+ database.append((filename, path, representation))
19
+ except:
20
+ print(f"❌ No se pudo procesar: {filename}")
21
+ return database
22
+
23
+ # Inicializamos base de datos
24
+ database = build_database()
25
 
26
+ # Comparar imagen cargada con las del dataset
27
+ def find_similar_faces(uploaded_image):
28
+ try:
29
+ uploaded_image = np.array(uploaded_image)
30
+ query_representation = DeepFace.represent(img_path=uploaded_image, model_name="Facenet")[0]["embedding"]
31
+ except:
32
+ return [], "⚠ No se detectó un rostro válido en la imagen."
 
 
 
33
 
34
+ similarities = []
35
+ for name, path, rep in database:
36
+ distance = np.linalg.norm(np.array(query_representation) - np.array(rep))
37
+ similarity = 1 / (1 + distance) # Normalizamos para que 1 = muy similar
38
+ similarities.append((similarity, name, path))
39
 
40
+ # Ordenar por similitud
41
+ similarities.sort(reverse=True)
42
+ top_matches = similarities[:5]
43
+
44
+ # Formatear salida para gradio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  gallery_items = []
46
+ text_summary = ""
47
+ for sim, name, path in top_matches:
48
+ img = Image.open(path)
49
+ caption = f"{name} - Similitud: {sim:.2f}"
 
 
50
  gallery_items.append({"image": img, "caption": caption})
51
+ text_summary += caption + "\n"
52
+
53
+ return gallery_items, text_summary
54
 
55
+ # Interfaz Gradio
56
  demo = gr.Interface(
57
+ fn=find_similar_faces,
58
+ inputs=gr.Image(label="📤 Sube una imagen", type="pil"),
59
  outputs=[
60
+ gr.Gallery(label="📸 Rostros más similares").style(grid=[2], height="auto"),
61
+ gr.Textbox(label="🧠 Similitud", lines=6)
62
  ],
63
+ title="🔍 Buscador de Rostros con DeepFace",
64
+ description="Sube una imagen y te mostrará los rostros más similares desde el directorio `dataset_faces/`."
65
  )
66
 
67
  demo.launch()
apt.txt DELETED
@@ -1,4 +0,0 @@
1
- cmake
2
- libboost-all-dev
3
- libgtk-3-dev
4
- build-essential
 
 
 
 
 
requirements.txt CHANGED
@@ -1,10 +1,5 @@
1
  gradio
2
  numpy
3
  Pillow
 
4
  opencv-python-headless
5
-
6
- # Usa face_recognition desde GitHub
7
- git+https://github.com/ageitgey/face_recognition.git
8
-
9
- # Asegura versión de dlib
10
- dlib==19.24.0
 
1
  gradio
2
  numpy
3
  Pillow
4
+ deepface
5
  opencv-python-headless