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
| import cv2 import threading import face_recognition import os import sys import ctypes
class watchdog(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.video_capture = cv2.VideoCapture(0) self.jump = True self.stop = True self.known_face_encodings = [] self.known_face_names = [] self.dll = ctypes.WinDLL('user32.dll') self.load_faces()
def run(self): num = 0 while self.stop: ret, frame = self.video_capture.read() small_frame = cv2.resize(frame,(0,0),fx=0.25,fy=0.25) rgb_small_frame = small_frame[:,:,::-1] if self.jump: face_locations,face_names = self.face_detection(rgb_small_frame) result_frame = self.result_processing(frame,face_locations,face_names) if len(face_names) > 0: for fn in face_names: if fn == 'Who are you?': num += 1 else: num = 0 if num >= 10: self.dll.LockWorkStation() num = 0 self.jump = not self.jump cv2.imshow('Video', result_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break self.video_capture.release() cv2.destroyAllWindows() def load_faces(self): """ 获取本地所有已存在人脸,一张图片一张脸,文件名称为姓名 """ path = sys.path[0] + '/face/' if not os.path.exists(path): os.mkdir(path) files = os.listdir(path) for f in files: fpath = path+f if os.path.isfile(fpath): if f[-3:].lower() == 'jpg' or f[-3:].lower() == 'jpeg': biden_image = face_recognition.load_image_file(fpath) biden_face_encoding = face_recognition.face_encodings(biden_image)[0] self.known_face_encodings.append(biden_face_encoding) self.known_face_names.append('.'.join(fpath.split('/')[-1].split('.')[:-1])) pass
def face_detection(self,rgb_small_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(self.known_face_encodings,face_encoding) name = 'Who are you?' if True in matches: first_match_index = matches.index(True) name = self.known_face_names[first_match_index] face_names.append(name) return face_locations,face_names
def result_processing(self,frame,face_locations,face_names): """ 结果处理 """ for (top,right,bottom,left), name in zip(face_locations,face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame,(left,top),(right,bottom),(0,0,255),2) cv2.rectangle(frame,(left,bottom-35),(right,bottom),(0,0,255),cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame,name,(left + 6,bottom -6),font,1.0,(255,255,255),1) return frame if __name__ == '__main__': wd = watchdog() wd.start() wd.join() pass
|