-
Notifications
You must be signed in to change notification settings - Fork 0
/
Recognition_Model.py
53 lines (52 loc) · 1.89 KB
/
Recognition_Model.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
import cv2
import numpy
import os
haar_file = 'haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(haar_file)
datasets = 'datasets'
(images, labels, names, ide) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(datasets):
for subdir in dirs:
names[ide] = subdir
subjectpath = os.path.join(datasets, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + '/' + filename
label = ide
images.append(cv2.imread(path, 0))
labels.append(int(label))
ide = ide + 1
(images, labels) = [numpy.array(lis) for lis in [images, labels]]
print(images, labels)
(width, height) = (130, 100)
model = cv2.face.LBPHFaceRecognizer_create()
#model = cv2.face.FisherFaceRecognizer_create()
model.train(images, labels)
cam = cv2.VideoCapture(0)
cnt = 0
while True:
(_, im) = cam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x, y), (x+w, y+h), (255, 255, 0), 2)
face = gray[y:y+h, x:x+h]
face_resize = cv2.resize(face, (width, height))
prediction = model.predict(face_resize)
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)
if prediction[1] < 800:
cv2.putText(im, '%s - %.0f' % (names[prediction[0]], prediction[1]), (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,
2, (0, 0, 255))
print(names[prediction[0]])
cnt = 0
else:
cnt += 1
cv2.putText(im, 'unknown', (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,
2, (0, 0, 255))
if cnt > 100:
print("unknown.jpg", im)
cv2.imwrite("unknown.jpg", im)
cnt = 0
cv2.imshow('FaceRecognition', im)
key = cv2.waitKey(10)
if key == 27:
break