-
Notifications
You must be signed in to change notification settings - Fork 205
/
main2.py
59 lines (47 loc) · 2.19 KB
/
main2.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
import cv2
import face_recognition
import numpy as np
import os
# Load known faces
known_face_encodings = []
known_face_names = []
# Load images from the 'images' directory
for filename in os.listdir('images'):
if filename.endswith('.jpg') or filename.endswith('.png'):
image_path = os.path.join('images', filename)
image = face_recognition.load_image_file(image_path)
encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(encoding)
known_face_names.append(os.path.splitext(filename)[0]) # Get the name without the extension
# Initialize video capture
video_capture = cv2.VideoCapture(0) # Use 0 for the default camera
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
# Convert the image from BGR to RGB
rgb_frame = frame[:, :, ::-1]
# Find all the faces and face encodings in the current frame
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# Loop through each face found in the frame
for face_encoding, face_location in zip(face_encodings, face_locations):
# Compare the found face with known faces
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# Use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
# Draw a rectangle around the face
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
# Display the resulting frame
cv2.imshow('Face Recognition', frame)
# Break the loop when 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture
video_capture.release()
cv2.destroyAllWindows()