[Python] 纯文本查看 复制代码
import os
import time
import cv2
import face_recognition
import numpy as np
import win32con
import win32gui
video_capture = cv2.VideoCapture(0)
img = cv2.imread("res/img.png")
path = os.getcwd()
os.chdir(path)
images_file = os.listdir(path+'/img')
known_face_encodings = []
known_face_names = []
for each in images_file:
image_path = path + '/img/'+each
known_face_encodings.append(face_recognition.face_encodings(face_recognition.load_image_file(image_path))[0])
name = os.path.splitext(each)[0]
known_face_names.append(name)
face_names = []
face_locations = []
face_encodings = []
process_this_frame = True
cascade = cv2.CascadeClassifier("./res/haarcascade_frontalface_default.xml") ## 读入分类器数据
i = 0
statTime = time.time()
endTime = time.time()
ck1 = False
while True:
if endTime - statTime > 10:
print("人脸消失超过10s,自动锁屏")
out_win = "output_style_full_screen"
cv2.namedWindow(out_win, cv2.WINDOW_NORMAL)
cv2.setWindowProperty(out_win, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
cv2.imshow(out_win, img)
#window前置
if ck1 == False:
hwnd = win32gui.FindWindow(None, out_win) # 获取句柄,然后置顶
CVRECT = cv2.getWindowImageRect(out_win)
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, CVRECT[2], CVRECT[3], win32con.SWP_SHOWWINDOW)
# cv2.waitKey(0)
ck1 = True
elif ck1 and endTime - statTime < 10:
cv2.destroyWindow(out_win)
ck1 = False
ret, frame = video_capture.read()
sample_image = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) ## 图片地址
faces = cascade.detectMultiScale(sample_image, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50))
if len(faces) > 0:
print("存在" + str(len(faces)) + "张人脸")
else:
# print("不存在人脸")
endTime = time.time()
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)
for name in face_names:
#print(name[0])
print(name)
if name in known_face_names:
statTime = time.time()
else:
endTime = time.time()
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)
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()