前言
最近突然有个奇妙的想法,就是当我对着电脑屏幕的时候,电脑会先识别屏幕上的人脸是否是本人,如果识别是本人的话需要回答电脑说的暗语,答对了才会解锁并且有三次机会。如果都没答对就会发送邮件给我,通知有人在动我的电脑并上传该人头像。
过程
环境是win10代码我使用的是python3所以在开始之前需要安装一些依赖包,请按顺序安装否者会报错
pip install cmake -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install dlib -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install face_recognition -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
接下来是构建识别人脸以及对比人脸的代码
import face_recognition
import cv2
import numpy as np
video_capture = cv2.VideoCapture(0)
my_image = face_recognition.load_image_file("my.jpg")
my_face_encoding = face_recognition.face_encodings(my_image)[0]
known_face_encodings = [
my_face_encoding
]
known_face_names = [
"Admin"
]
face_names = []
face_locations = []
face_encodings = []
process_this_frame = True
while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1]
if process_this_frame:
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:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
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]
face_names.append(name)
process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
left *= 4
right *= 4
bottom *= 4
font = cv2.FONT_HERSHEY_DUPLEX
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)