-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
221 lines (177 loc) · 7.4 KB
/
Copy pathmain.py
File metadata and controls
221 lines (177 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import cv2
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from eigenface import train_eigenfaces
matplotlib.use('TkAgg')
from sklearn.metrics import confusion_matrix
import seaborn as sns
from camera_capture import run_face_recognition_camera
def plot_confusion_matrix(y_true, y_pred):
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=False, cmap="Blues") # annot=True si peu de classes
plt.xlabel('Predit')
plt.ylabel('Vrai')
plt.title('Matrice de Confusion')
plt.show()
def load_image(folder_path):
images = []
person = []
img_shape = None
person_folders = os.listdir(folder_path)
for person_image in person_folders:
person_path = os.path.join(folder_path, person_image)
if not os.path.isdir(person_path):
continue
for image_name in os.listdir(person_path):
image_path = os.path.join(person_path, image_name)
img = cv2.imread(image_path, 0)
if img is None:
continue
if img_shape is None:
img_shape = img.shape
img_flat = img.flatten()
images.append(img_flat)
person.append(person_image)
images = np.array(images, dtype=np.float32)
person = np.array(person)
print(f"Dimension de la matrice X : {images.shape}")
return images, person, img_shape
# --- Projection fonction ---
def get_weights(data, mean_face, eigenfaces):
"""Calcule la signature (poids) des images"""
data_centered = data - mean_face
weights = np.dot(data_centered, eigenfaces)
return weights
# --- Prediction fonction ---
def predict_face(test_image, mean_face, eigenfaces, train_weights, train_labels):
test_image_centered = test_image - mean_face
test_weight = np.dot(test_image_centered.reshape(1, -1), eigenfaces)
distances = np.linalg.norm(train_weights - test_weight, axis=1)
min_dist_index = np.argmin(distances)
min_dist = distances[min_dist_index]
predicted_label = train_labels[min_dist_index]
return predicted_label, min_dist
def analyze_performance(X_train, y_train, X_test, y_test):
components_list = [5, 10, 20, 30, 50, 100]
accuracies = []
for n in components_list:
print(f"Test avec {n} composantes...")
mean, eigenfaces, _ = train_eigenfaces(X_train, n)
train_weights = get_weights(X_train, mean, eigenfaces)
correct = 0
for i in range(len(X_test)):
pred, _ = predict_face(X_test[i], mean, eigenfaces, train_weights, y_train)
if pred == y_test[i]:
correct += 1
acc = correct / len(X_test)
accuracies.append(acc)
plt.plot(components_list, accuracies, marker='o')
plt.xlabel("Nombre d'Eigenfaces")
plt.ylabel("Précision")
plt.title("Impact de la réduction de dimension sur la précision")
plt.grid()
plt.show()
def reconstruct_image(image_originale, mean_face, eigenfaces):
image_centered = image_originale.flatten() - mean_face
weights = np.dot(image_centered, eigenfaces)
reconstruction = np.dot(weights, eigenfaces.T) + mean_face
return reconstruction
def main_menu():
"""Menu principal pour choisir le mode d'exécution"""
print("\n" + "="*60)
print(" SYSTÈME DE RECONNAISSANCE FACIALE PAR EIGENFACES")
print("="*60)
print("\n1. Exécuter l'analyse complète (Test + Graphiques)")
print("2. Lancer la reconnaissance faciale en temps réel (Caméra)")
print("3. Quitter")
print("\n" + "="*60)
def run_analysis():
"""Exécute l'analyse complète avec graphiques"""
chemin_dataset = "./face_database"
try:
images, labels, shape = load_image(chemin_dataset)
np.random.seed(42)
indices = np.arange(len(images))
np.random.shuffle(indices)
images = images[indices]
labels = labels[indices]
# 3. Séparation Train / Test
num_test_image = 50
X_train = images[:-num_test_image]
y_train = labels[:-num_test_image]
X_test = images[-num_test_image:]
y_test = labels[-num_test_image:]
# 4. Entraînement (Calcul des Eigenfaces)
print("\n--- Entraînement en cours ---")
mean_face, eigenfaces, X_centered = train_eigenfaces(X_train, n_components=50)
train_weights = get_weights(X_train, mean_face, eigenfaces)
# 5. Visualisation (Visage Moyen et Eigenface)
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.imshow(mean_face.reshape(shape), cmap='gray')
plt.title("Le Visage Moyen")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(eigenfaces[:, 0].reshape(shape), cmap='gray')
plt.title("Eigenface #1 (Ghost Face)")
plt.axis('off')
plt.show(block=False)
plt.pause(2)
plt.close()
# 6. Test de Reconnaissance Standard
print("\n--- DÉBUT DU TEST DE RECONNAISSANCE ---")
correct = 0
for i in range(len(X_test)):
label_predit, distance = predict_face(X_test[i], mean_face, eigenfaces, train_weights, y_train)
vrai_label = y_test[i]
if i < 5:
status = "OK" if label_predit == vrai_label else "ERREUR"
print(f"Image {i+1}: Vrai={vrai_label} | Predit={label_predit} (Dist={distance:.2f}) -> {status}")
if label_predit == vrai_label:
correct += 1
precision = (correct / len(X_test)) * 100
print(f"\n>>> PRÉCISION FINALE (50 composantes) : {precision:.2f}%")
# 7. PARTIE RECHERCHE : Courbe de performance
print("\n--- ANALYSE DE PERFORMANCE (Courbe) ---")
print("Calcul en cours pour 5, 10, 20... composantes. Patientez.")
analyze_performance(X_train, y_train, X_test, y_test)
# 8. PARTIE MATHÉMATIQUE : Reconstruction
print("\n--- DÉMONSTRATION DE RECONSTRUCTION ---")
image_test = X_test[0]
reconstruction = reconstruct_image(image_test, mean_face, eigenfaces)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image_test.reshape(shape), cmap='gray')
plt.title(f"Originale ({y_test[0]})")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(reconstruction.reshape(shape), cmap='gray')
plt.title("Reconstruite avec 50 Eigenfaces")
plt.axis('off')
plt.show()
except Exception as e:
print(f"Erreur critique : {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
while True:
main_menu()
choix = input("\nChoisissez une option (1, 2 ou 3): ").strip()
if choix == "1":
print("\n Démarrage de l'analyse complète...")
run_analysis()
elif choix == "2":
print("\n Démarrage de la reconnaissance faciale en temps réel...")
run_face_recognition_camera(
dataset_path="./face_database",
n_components=50,
threshold=5000
)
elif choix == "3":
print(" Au revoir!")
break
else:
print(" Option invalide. Veuillez entrer 1, 2 ou 3.")