-
Notifications
You must be signed in to change notification settings - Fork 1
/
simple_facerec.py
66 lines (54 loc) · 2.61 KB
/
simple_facerec.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
import face_recognition
import cv2
import os
import glob
import numpy as np
class SimpleFacerec:
def __init__(self):
self.known_face_encodings = []
self.known_face_names = []
# Resize frame for a faster speed
self.frame_resizing = 0.25
def load_encoding_images(self, images_path):
"""
Load encoding images from path
:param images_path:
:return:
"""
# Load Images
images_path = glob.glob(os.path.join(images_path, "*.*"))
print("{} encoding images found.".format(len(images_path)))
# Store image encoding and names
for img_path in images_path:
img = cv2.imread(img_path)
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Get the filename only from the initial file path.
basename = os.path.basename(img_path)
(filename, ext) = os.path.splitext(basename)
# Get encoding
img_encoding = face_recognition.face_encodings(rgb_img)[0]
# Store file name and file encoding
self.known_face_encodings.append(img_encoding)
self.known_face_names.append(filename)
print("Encoding images loaded")
def detect_known_faces(self, frame):
small_frame = cv2.resize(frame, (0, 0), fx=self.frame_resizing, fy=self.frame_resizing)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(self.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(self.known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = self.known_face_names[best_match_index]
face_names.append(name)
# Convert to numpy array to adjust coordinates with frame resizing quickly
face_locations = np.array(face_locations)
face_locations = face_locations / self.frame_resizing
return face_locations.astype(int), face_names