-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverbasign.py
More file actions
204 lines (164 loc) · 6.29 KB
/
verbasign.py
File metadata and controls
204 lines (164 loc) · 6.29 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
import cv2
import os
import numpy as np
from config import DATA_PATH, HAARCASCADE_PATH, TRAINER_YML_PATH
def get_face_cascade():
cascade_path = cv2.data.haarcascades + HAARCASCADE_PATH
return cv2.CascadeClassifier(cascade_path)
def collect_dataset():
"""
Capture face images from the webcam and save them for a given person.
Press 'ESC' to exit or until 500 images are collected.
"""
name = input("Enter your name for the LBPH dataset collection: ").strip()
if not name:
print("Name cannot be empty.")
return
save_dir = os.path.join(DATA_PATH, name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
face_cascade = get_face_cascade()
if face_cascade.empty():
print("Error loading face cascade.")
return
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error opening webcam.")
return
# Count how many images already exist in the folder
existing_files = [f for f in os.listdir(save_dir) if f.lower().endswith(('.jpg', '.png'))]
count = len(existing_files)
print("Press 'c' to capture a face. Press 'ESC' to finish.")
while True:
ret, frame = cap.read()
if not ret:
break
key = cv2.waitKey(1)
frame = cv2.flip(frame, 1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(100, 100)
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
if key & 0xFF == ord('c'):
count += 1
face_img = gray[y:y+h, x:x+w]
face_img = cv2.resize(face_img, (200, 200))
file_path = os.path.join(save_dir, f"{count}.jpg")
cv2.imwrite(file_path, face_img)
print(f"Captured {count} images and saved to {file_path}")
cv2.imshow("Collecting Faces for LBPH", frame)
if key == 27 or count >= 500: # ESC Key or max images
break
cap.release()
cv2.destroyAllWindows()
print("Dataset collection completed.")
def train_recognizer():
"""
Train the LBPH face recognizer using images stored in the dataset folder.
"""
print("Training LBPH model...")
face_cascade = get_face_cascade()
if not os.path.exists(DATA_PATH):
print(f"Dataset path {DATA_PATH} not found.")
return None, None
recognizer = cv2.face.LBPHFaceRecognizer_create()
face_samples = []
labels = []
label_dict = {}
current_label = 0
for person_name in sorted(os.listdir(DATA_PATH)):
person_dir = os.path.join(DATA_PATH, person_name)
if not os.path.isdir(person_dir):
continue
label_dict[current_label] = person_name
for image_name in os.listdir(person_dir):
if image_name.lower().endswith((".jpg", ".png", ".jpeg")):
img_path = os.path.join(person_dir, image_name)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is None:
continue
faces = face_cascade.detectMultiScale(img)
for (x, y, w, h) in faces:
face_roi = cv2.resize(img[y:y+h, x:x+w], (200, 200))
face_samples.append(face_roi)
labels.append(current_label)
current_label += 1
if len(face_samples) == 0:
print("No face images found in the dataset.")
return None, None
recognizer.train(face_samples, np.array(labels))
recognizer.save(TRAINER_YML_PATH)
print(f"Training completed. Trainer saved to {TRAINER_YML_PATH}")
return recognizer, label_dict
def recognize_face(recognizer, label_dict):
"""
Recognize faces using the trained LBPH recognizer.
"""
print("Starting face recognition... Press 'ESC' to exit.")
face_cascade = get_face_cascade()
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(100, 100)
)
for (x, y, w, h) in faces:
roi_gray = gray[y:y+h, x:x+w]
roi_gray = cv2.resize(roi_gray, (200, 200))
label, confidence = recognizer.predict(roi_gray)
if confidence < 70:
name = label_dict.get(label, "Unknown")
else:
name = "Unknown"
text = f"{name} ({confidence:.2f})"
cv2.putText(frame, text, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow("LBPH Face Recognition", frame)
if cv2.waitKey(1) == 27: # ESC to exit
break
cap.release()
cv2.destroyAllWindows()
def main():
print("Welcome to Face Recognition (LBPH approach)")
print("1: Collect Dataset")
print("2: Train Recognizer")
print("3: Live Recognition")
print("4: Exit")
choice = input("Enter choice (1-4): ").strip()
if choice == '1':
collect_dataset()
elif choice == '2':
train_recognizer()
elif choice == '3':
if not os.path.exists(TRAINER_YML_PATH):
print(f"Error: Trained model '{TRAINER_YML_PATH}' not found. Train first.")
return
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read(TRAINER_YML_PATH)
# Determine the label dictionary from the data directory
# Warning: This assumes directories haven't changed since training.
# Alternatively, save label_dict together with the model using pickle.
label_dict = {}
if os.path.exists(DATA_PATH):
for i, d in enumerate(sorted(os.listdir(DATA_PATH))):
if os.path.isdir(os.path.join(DATA_PATH, d)):
label_dict[i] = d
recognize_face(recognizer, label_dict)
elif choice == '4':
return
else:
print("Invalid choice.")
if __name__ == "__main__":
main()