moustaphasidibe commited on
Commit
5c72cf8
·
verified ·
1 Parent(s): 2b9d314

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -65
app.py CHANGED
@@ -2,102 +2,107 @@ import os
2
  import cv2
3
  import dlib
4
  import numpy as np
 
5
  import gradio as gr
6
  import git
7
- from PIL import Image
8
 
9
- # === CONFIGURATION ===
10
  REPO_URL = "https://github.com/Moustapha224/Reconnaissance"
11
- CLONE_DIR = "Reconnaissance"
12
- KNOWN_FACES_DIR = os.path.join(CLONE_DIR, "Known_faces")
13
 
14
- # === CLONAGE DU DÉPÔT GITHUB ===
15
- if not os.path.exists(CLONE_DIR):
16
  print(f"🔄 Clonage du dépôt GitHub depuis {REPO_URL} ...")
17
- git.Repo.clone_from(REPO_URL, CLONE_DIR)
18
 
19
- # === DLIB MODELS ===
20
- PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
21
- FACE_ENCODER_PATH = "dlib_face_recognition_resnet_model_v1.dat"
22
  face_detector = dlib.get_frontal_face_detector()
23
- shape_predictor = dlib.shape_predictor(PREDICTOR_PATH)
24
- face_encoder = dlib.face_recognition_model_v1(FACE_ENCODER_PATH)
25
 
26
- # === ENCODAGE DES VISAGES CONNUS ===
27
- known_encodings = []
28
- known_names = []
29
 
 
30
  def get_face_encoding(image):
31
- if image is None or len(image.shape) != 3 or image.shape[2] != 3:
32
- return None
 
 
 
 
 
33
  dets = face_detector(image, 1)
34
  if len(dets) == 0:
35
  return None
 
36
  shape = shape_predictor(image, dets[0])
37
- encoding = face_encoder.compute_face_descriptor(image, shape)
38
- return np.array(encoding)
39
 
 
40
  def load_known_faces():
41
  print("🔍 Encodage des visages connus...")
42
- for person_name in os.listdir(KNOWN_FACES_DIR):
43
- person_dir = os.path.join(KNOWN_FACES_DIR, person_name)
44
- if not os.path.isdir(person_dir):
45
  continue
46
- for filename in os.listdir(person_dir):
47
- file_path = os.path.join(person_dir, filename)
48
  try:
49
- # On charge via PIL pour garantir le format
50
- with Image.open(file_path) as img:
51
- img = img.convert("RGB")
52
- img_np = np.array(img)
53
- encoding = get_face_encoding(img_np)
54
  if encoding is not None:
55
- known_encodings.append(encoding)
56
- known_names.append(person_name)
57
  else:
58
- print(f"⚠️ Visage non détecté dans : {file_path}")
59
  except Exception as e:
60
- print(f"❌ Problème avec {file_path}: {e}")
61
 
62
  load_known_faces()
63
 
64
- # === RECONNAISSANCE ===
65
- def recognize_faces(uploaded_image):
 
 
66
  try:
67
- if uploaded_image is None:
68
- print("⚠️ Image reçue est None")
69
- return None
70
- img = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2RGB)
71
- dets = face_detector(img, 1)
72
- for det in dets:
73
- shape = shape_predictor(img, det)
74
- encoding = face_encoder.compute_face_descriptor(img, shape)
75
- encoding_np = np.array(encoding)
76
-
77
- distances = np.linalg.norm(known_encodings - encoding_np, axis=1)
78
- name = "Inconnu"
79
- if len(distances) > 0:
80
- min_idx = np.argmin(distances)
81
- if distances[min_idx] < 0.6:
82
- name = known_names[min_idx]
83
-
84
- x, y, x1, y1 = det.left(), det.top(), det.right(), det.bottom()
85
- cv2.rectangle(uploaded_image, (x, y), (x1, y1), (0, 255, 0), 2)
86
- cv2.putText(uploaded_image, name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
87
-
88
- return cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2RGB)
89
- except Exception as e:
90
- print(f"❌ Erreur dans recognize_faces: {e}")
91
  return None
92
 
93
- # === INTERFACE GRADIO ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  iface = gr.Interface(
95
  fn=recognize_faces,
96
- inputs=gr.Image(type="numpy", label="Uploader une image"),
97
- outputs=gr.Image(type="numpy", label="Résultat"),
98
  title="Reconnaissance Faciale",
99
- description="Uploader une photo pour identifier les visages connus."
100
  )
101
 
102
- if __name__ == "__main__":
103
- iface.launch()
 
2
  import cv2
3
  import dlib
4
  import numpy as np
5
+ from PIL import Image
6
  import gradio as gr
7
  import git
 
8
 
9
+ # === Clone le dépôt GitHub contenant Known_faces_clean ===
10
  REPO_URL = "https://github.com/Moustapha224/Reconnaissance"
11
+ REPO_DIR = "Reconnaissance"
12
+ KNOWN_FACES_DIR = os.path.join(REPO_DIR, "Known_faces_clean")
13
 
14
+ if not os.path.exists(REPO_DIR):
 
15
  print(f"🔄 Clonage du dépôt GitHub depuis {REPO_URL} ...")
16
+ git.Repo.clone_from(REPO_URL, REPO_DIR)
17
 
18
+ # === Initialisation des outils Dlib ===
 
 
19
  face_detector = dlib.get_frontal_face_detector()
20
+ shape_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
21
+ face_rec_model = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")
22
 
23
+ # === Stockage des visages connus ===
24
+ known_face_encodings = []
25
+ known_face_names = []
26
 
27
+ # === Fonction d'encodage d'une image en vecteur de visage ===
28
  def get_face_encoding(image):
29
+ if image is None or len(image.shape) != 3:
30
+ raise ValueError("Image invalide (None ou pas RGB)")
31
+ if image.shape[2] == 4:
32
+ image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
33
+ elif image.shape[2] != 3:
34
+ image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
35
+
36
  dets = face_detector(image, 1)
37
  if len(dets) == 0:
38
  return None
39
+
40
  shape = shape_predictor(image, dets[0])
41
+ face_descriptor = face_rec_model.compute_face_descriptor(image, shape)
42
+ return np.array(face_descriptor)
43
 
44
+ # === Chargement des visages connus ===
45
  def load_known_faces():
46
  print("🔍 Encodage des visages connus...")
47
+ for person in os.listdir(KNOWN_FACES_DIR):
48
+ person_path = os.path.join(KNOWN_FACES_DIR, person)
49
+ if not os.path.isdir(person_path):
50
  continue
51
+ for file in os.listdir(person_path):
52
+ file_path = os.path.join(person_path, file)
53
  try:
54
+ img = Image.open(file_path).convert("RGB")
55
+ rgb = np.array(img)
56
+ encoding = get_face_encoding(rgb)
 
 
57
  if encoding is not None:
58
+ known_face_encodings.append(encoding)
59
+ known_face_names.append(person)
60
  else:
61
+ print(f"⚠️ Aucun visage détecté dans {file_path}")
62
  except Exception as e:
63
+ print(f"❌ Erreur avec {file_path}: {e}")
64
 
65
  load_known_faces()
66
 
67
+ # === Fonction de reconnaissance faciale ===
68
+ def recognize_faces(image):
69
+ if image is None:
70
+ return None
71
  try:
72
+ img = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2RGB if image.mode == "RGBA" else cv2.COLOR_RGB2BGR)
73
+ except:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  return None
75
 
76
+ dets = face_detector(img, 1)
77
+ if len(dets) == 0:
78
+ return image
79
+
80
+ for d in dets:
81
+ shape = shape_predictor(img, d)
82
+ face_descriptor = face_rec_model.compute_face_descriptor(img, shape)
83
+ encoding = np.array(face_descriptor)
84
+
85
+ distances = np.linalg.norm(known_face_encodings - encoding, axis=1)
86
+ min_distance = np.min(distances)
87
+ name = "Inconnu"
88
+
89
+ if min_distance < 0.6:
90
+ name = known_face_names[np.argmin(distances)]
91
+
92
+ # Dessiner le rectangle
93
+ x1, y1, x2, y2 = d.left(), d.top(), d.right(), d.bottom()
94
+ cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
95
+ cv2.putText(img, name, (x1, y2 + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
96
+
97
+ return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
98
+
99
+ # === Interface Gradio ===
100
  iface = gr.Interface(
101
  fn=recognize_faces,
102
+ inputs=gr.Image(label="Image à reconnaître"),
103
+ outputs=gr.Image(label="Résultat"),
104
  title="Reconnaissance Faciale",
105
+ description="Téléversez une image contenant un visage pour l'identifier à partir des visages connus."
106
  )
107
 
108
+ iface.launch()