-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdef_face.py
164 lines (140 loc) · 6.35 KB
/
def_face.py
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
import cv2
import pandas as pd
import numpy as np
from datetime import datetime
from transformers import AutoModel, AutoFeatureExtractor
from PIL import Image
from scipy.spatial.distance import cosine
import os
# === 1. Modelni yuklash ===
def load_model():
model_name = "google/vit-base-patch16-224-in21k"
try:
print("Model yuklanmoqda...")
model = AutoModel.from_pretrained(model_name)
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
print("Model muvaffaqiyatli yuklandi.")
return model, feature_extractor
except Exception as e:
print(f"Model yuklashda xatolik: {e}")
exit()
# === 2. Yuz embeddinglarini olish ===
def get_face_embedding(model, feature_extractor, image):
try:
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
inputs = feature_extractor(images=pil_image, return_tensors="pt")
outputs = model(**inputs)
embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().detach().numpy()
return embeddings
except Exception as e:
print(f"Xatolik embedding olishda: {e}")
return None
# === 3. O'xshashlikni hisoblash ===
def calculate_similarity(embedding1, embedding2):
try:
return 1 - cosine(embedding1, embedding2)
except Exception as e:
print(f"O'xshashlikni hisoblashda xatolik: {e}")
return 0
# === 4. Yuzlar ma'lumotini saqlash va terminalda chiqarish ===
def save_detected_faces_to_excel_and_print(name, similarity, gender, timestamp):
file_name = "detected_faces.xlsx"
new_data = {
"Timestamp": [timestamp],
"Name": [name],
"Gender": [gender],
"Similarity": [similarity]
}
df_new = pd.DataFrame(new_data)
# Terminalda ma'lumotlarni chiqarish
print(df_new)
try:
if os.path.exists(file_name):
with pd.ExcelWriter(file_name, mode="a", if_sheet_exists="overlay", engine="openpyxl") as writer:
df_new.to_excel(writer, index=False, header=False, startrow=writer.sheets['Sheet1'].max_row)
else:
df_new.to_excel(file_name, index=False)
except PermissionError:
print(f"Xatolik: '{file_name}' fayli boshqa dastur tomonidan foydalanilmoqda. Uni yoping va qayta urinib ko'ring.")
# === 5. Genderni aniqlash ===
def predict_gender(name):
gender_mapping = {
"Kim Songmin": "male",
"Kim Yeongho": "male",
"Lee Jeak": "male",
"Umida": "female"
}
return gender_mapping.get(name, "Unknown")
# === 6. Kameradan real vaqt rejimida yuzlarni tanib olish ===
def detect_and_compare_faces(model, feature_extractor, reference_embeddings, reference_names):
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Kamera ochilmadi. Qurilmani tekshiring.")
return
print("Kameradan yuzlarni qidirishni boshlash. ESC tugmasini bosing chiqish uchun.")
logged_names = set() # Yuzlarni bir marta log qilish uchun to'plam
while True:
ret, frame = cap.read()
if not ret:
print("Kamera bilan muammo yuz berdi.")
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=7, minSize=(100, 100))
for (x, y, w, h) in faces:
face = frame[y:y + h, x:x + w]
embedding = get_face_embedding(model, feature_extractor, face)
if embedding is not None:
similarities = [calculate_similarity(embedding, ref_emb) for ref_emb in reference_embeddings]
max_similarity = max(similarities)
best_match_index = similarities.index(max_similarity)
name = reference_names[best_match_index] if max_similarity > 0.70 else "Unknown"
# Genderni aniqlash
gender = predict_gender(name)
# Yuz ramkasi va ism
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
label = f"{name}: {max_similarity:.2f}, {gender}"
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Ismni bir marta log qilish
if name not in logged_names and name != "Unknown":
print(f"Detected: {name} ({gender})")
logged_names.add(name)
# Yuz ma'lumotlarini Excel faylga saqlash va terminalda chiqarish
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
save_detected_faces_to_excel_and_print(name, f"{max_similarity:.2f}", gender, timestamp)
# Tasvirni ko'rsatish
cv2.imshow("Real-Time Face Recognition", frame)
if cv2.waitKey(1) & 0xFF == 27: # ESC tugmasi bilan chiqish
break
cap.release()
cv2.destroyAllWindows()
# === 7. Asosiy kodni ishga tushirish ===
def main():
model, feature_extractor = load_model()
# Referens tasvirlar va ismlar
reference_images = [
r"C:\Users\13\Desktop\face_recog\Kim Songmin.jpg",
r"C:\Users\13\Desktop\face_recog\Kim Yeongho.jpg",
r"C:\Users\13\Desktop\face_recog\Lee Jeak.jpg",
r"C:\Users\13\Desktop\face_recog\Umida.jpg"
]
reference_names = ["Kim Songmin", "Kim Yeongho", "Lee Jeak", "Umida"]
# Referens embeddinglarini olish
reference_embeddings = []
for image_path, name in zip(reference_images, reference_names):
if not os.path.exists(image_path):
print(f"Tasvir mavjud emas: {image_path}")
continue
image = cv2.imread(image_path)
if image is not None:
embedding = get_face_embedding(model, feature_extractor, image)
if embedding is not None:
reference_embeddings.append(embedding)
else:
print(f"{name} uchun embeddinglarni olishda muammo yuz berdi.")
else:
print(f"Tasvir ochib bo'lmadi: {image_path}")
if reference_embeddings:
detect_and_compare_faces(model, feature_extractor, reference_embeddings, reference_names)
else:
print("Referens embeddinglar topilmadi.")