-
Notifications
You must be signed in to change notification settings - Fork 0
/
face_recognition.py
77 lines (55 loc) · 2.39 KB
/
face_recognition.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
import numpy as np
import cv2 as cv
# Load the cascade
haar_cascade = cv.CascadeClassifier('haar_face.xml')
people = ['Mike Iannotti', 'Elton John']
face_recognizer = cv.face.LBPHFaceRecognizer_create()
face_recognizer.read('face_trained.yml')
# 0 for windows webcam, 0 for iphone external camera on macos
# 1 for macos webcam.
# Define video capture (index)
cap = cv.VideoCapture(0)
while cap.isOpened():
# capture each frame
ret, frame = cap.read()
# convert frame to grayscale
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Detect the face in the frame
faces_rect = haar_cascade.detectMultiScale(gray, 1.3, 5)
for(x,y,w,h) in faces_rect:
faces_roi = gray[y:y+h, x:x+h]
label, confidence = face_recognizer.predict(faces_roi)
print(f'Label = {people[label]} with a confidence of {confidence}')
cv.putText(frame, str(people[label]), (x,y), cv.FONT_HERSHEY_COMPLEX, 1.0, (0,255,0), thickness=2)
cv.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), thickness=2)
cv.imshow('Detected Face', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# # Release the capture and close all windows
cap.release()
cv.destroyAllWindows()
# # Function to detect faces and draw rectangles
# def detect_faces_in_video():
# # Open webcam
# cap = cv.VideoCapture(0, cv.CAP_DSHOW)
# while True:
# # Read the frame
# ret, frame = cap.read()
# # convert frame to grayscale
# gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# # Detect faces in grayscale fram
# faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# # Draw rectangle around each face
# for (x, y, w, h) in faces:
# cv.putText(frame, 'Mike Iannotti', (x, y-10), cv.FONT_HERSHEY_COMPLEX, 1.0, (0, 255, 0), thickness=2)
# cv.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
# # Display the output with rectangles and text added
# cv.imshow('Webcam - Press "q" to exit', frame)
# # Exit on 'q' key press
# if cv.waitKey(1) & 0xFF == ord('q'):
# break
# # Release the capture and close all windows
# cap.release()
# cv.destroyAllWindows()
# # Call the function to detect faces in video
# detect_faces_in_video()