-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathface_model.py
More file actions
137 lines (80 loc) · 2.61 KB
/
Copy pathface_model.py
File metadata and controls
137 lines (80 loc) · 2.61 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
import cv2
import numpy as np
import os
def createUser(id, name):
cam = cv2.VideoCapture(0)
face_detector = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
count = 0
os.makedirs(f"dataset/{name}", exist_ok=True)
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in faces:
count += 1
face_img = gray[y:y+h, x:x+w]
cv2.imwrite(
f"dataset/{name}/{count}.jpg",
face_img
)
if count >= 50:
print("Done Capturing Images")
break
cam.release()
def train():
import os
import cv2
import numpy as np
dataset_path = "dataset"
recognizer = cv2.face.LBPHFaceRecognizer_create()
faces = []
labels = []
label_map = {}
label_id = 0
for person in os.listdir(dataset_path):
person_path = os.path.join(dataset_path, person)
# skip hidden files like .DS_Store
if not os.path.isdir(person_path):
continue
label_map[label_id] = person
for img_name in os.listdir(person_path):
img_path = os.path.join(person_path, img_name)
# skip non images
if not img_name.endswith(".jpg"):
continue
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
if img is None:
continue
faces.append(img)
labels.append(label_id)
label_id += 1
print("Faces collected:", len(faces))
if len(faces) == 0:
print("No faces found for training")
return
recognizer.train(faces, np.array(labels))
recognizer.save("trainer.yml")
np.save("labels.npy", label_map)
print("Model trained successfully")
def recognize():
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")
labels = np.load("labels.npy", allow_pickle=True).item()
cam = cv2.VideoCapture(0)
face_detector = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
name = "Unknown"
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
id, confidence = recognizer.predict(gray[y:y+h, x:x+w])
if confidence < 80:
name = labels[id]
break
cam.release()
return name