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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| """ 人脸识别认证
使用摄像头检验当前用户是否匹配 """
import cv2 import os import face_recognition import pyautogui import time
class AuthByFace:
def __init__(self, clicked, clocked): self.clicked = clicked self.clocked = clocked self.SUCCESS_DIR = os.environ['HOME'] + "/Pictures/authFaces/success/"
def isAuthSuccess(self):
cameraCapture = cv2.VideoCapture(0) result, image = cameraCapture.read() if result: cameraImageFaceLocations = face_recognition.face_locations(image) cameraImageEncodings = face_recognition.face_encodings(image, cameraImageFaceLocations)[0]
personNames = [] knownImageEncodings = [] files = os.listdir(self.SUCCESS_DIR) for file in files: if file.endswith("jpg") or file.endswith("png"): name, _ = os.path.split(file) personNames.append(name) knowImagePath = self.SUCCESS_DIR + file knownImage = face_recognition.load_image_file(knowImagePath) knownImageEncodings.append(face_recognition.face_encodings(knownImage)[0])
matchs = face_recognition.compare_faces(knownImageEncodings, cameraImageEncodings) print("hhaha", matchs) for index, match in enumerate(matchs): if match: print("图像: ", personNames[index], "匹配成功") return True
def onMouse(self, event, x, y, flags, param): if event == cv2.EVENT_LBUTTONUP: self.clicked = True
def savePicture(self): cameraCapture = cv2.VideoCapture(0) if not cameraCapture.isOpened(): print("摄像头未打开~~") exit() cameraCapture.set(3, 100) cameraCapture.set(4, 100) cv2.namedWindow('MyWindow') cv2.setMouseCallback('MyWindow', self.onMouse) print('showing camera feed. Click window or press and key to stop.') result, image = cameraCapture.read() print(result)
while result and cv2.waitKey(1) == -1 and not self.clicked: cv2.imshow('MyWindow', cv2.flip(image, 0)) result, image = cameraCapture.read() name = self.SUCCESS_DIR + 'image_0.jpg' cv2.imwrite(name, image) cv2.destroyWindow('MyWindow') cameraCapture.release()
if __name__ == '__main__': authByFace = AuthByFace(False, False)
files = os.listdir(authByFace.SUCCESS_DIR) if len(files) < 1: authByFace.savePicture() else: while True: time.sleep(10) try: isSuccess = authByFace.isAuthSuccess() if authByFace.clocked and isSuccess: print("认证通过") pyautogui.typewrite("1") pyautogui.press("enter") pyautogui.press("Esc") authByFace.clocked = False elif not isSuccess: pyautogui.hotkey('win', 'c') pyautogui.press(['l'], interval=0.1) authByFace.clocked = True except Exception as exc: print(type(exc)) if not authByFace.clocked: pyautogui.hotkey('win', 'c') pyautogui.press(['l'], interval=0.1) authByFace.clocked = True
|